Double compare java что делает
Перейти к содержимому

Double compare java что делает

  • автор:

Java.lang.Double.compare() Method

d2 − This is the second double to compare.

Return Value

This method returns the value 0 if d1 is numerically equal to d2; a value less than 0 if d1 is numerically less than d2; and a value greater than 0 if d1 is numerically greater than d2.

Exception

Example

The following example shows the usage of java.lang.Double.compare() method.

Let us compile and run the above program, this will produce the following result −

Class Double

In addition, this class provides several methods for converting a double to a String and a String to a double , as well as other constants and methods useful when dealing with a double .

This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.

Floating-point Equality, Equivalence, and Comparison

An equivalence relation on a set of values is a boolean relation on pairs of values that is reflexive, symmetric, and transitive. For more discussion of equivalence relations and object equality, see the Object.equals specification. An equivalence relation partitions the values it operates over into sets called equivalence classes. All the members of the equivalence class are equal to each other under the relation. An equivalence class may contain only a single member. At least for some purposes, all the members of an equivalence class are substitutable for each other. In particular, in a numeric expression equivalent values can be substituted for one another without changing the result of the expression, meaning changing the equivalence class of the result of the expression.

  • If v1 and v2 are both NaN, then v1 == v2 has the value false . Therefore, for two NaN arguments the reflexive property of an equivalence relation is not satisfied by the == operator.
  • If v1 represents +0.0 while v2 represents -0.0 , or vice versa, then v1 == v2 has the value true even though +0.0 and -0.0 are distinguishable under various floating-point operations. For example, 1.0/+0.0 evaluates to positive infinity while 1.0/-0.0 evaluates to negative infinity and positive infinity and negative infinity are neither equal to each other nor equivalent to each other. Thus, while a signed zero input most commonly determines the sign of a zero result, because of dividing by zero, +0.0 and -0.0 may not be substituted for each other in general. The sign of a zero input also has a non-substitutable effect on the result of some math library methods.

For ordered comparisons using the built-in comparison operators ( < , <= , etc.), NaN values have another anomalous situation: a NaN is neither less than, nor greater than, nor equal to any value, including itself. This means the trichotomy of comparison does not hold.

To provide the appropriate semantics for equals and compareTo methods, those methods cannot simply be wrappers around == or ordered comparison operations. Instead, equals uses representation equivalence, defining NaN arguments to be equal to each other, restoring reflexivity, and defining +0.0 to not be equal to -0.0 . For comparisons, compareTo defines a total order where -0.0 is less than +0.0 and where a NaN is equal to itself and considered greater than positive infinity.

The operational semantics of equals and compareTo are expressed in terms of bit-wise converting the floating-point values to integral values.

The natural ordering implemented by compareTo is consistent with equals. That is, two objects are reported as equal by equals if and only if compareTo on those objects returns zero.

The adjusted behaviors defined for equals and compareTo allow instances of wrapper classes to work properly with conventional data structures. For example, defining NaN values to be equals to one another allows NaN to be used as an element of a HashSet or as the key of a HashMap . Similarly, defining compareTo as a total ordering, including +0.0 , -0.0 , and NaN, allows instances of wrapper classes to be used as elements of a SortedSet or as keys of a SortedMap .

What is the Double.compare() Method in Java

In Java, there can be situations where the programmer needs to compare complex sort of values that can’t be analyzed easily. For instance, analyzing the identical values having differences in their decimal point values. In such situations, the “Double.compare()” method in Java is assistive in determining the equivalent, greater, or smaller values by returning the allocated returned values in each case.

This article will elaborate on using and implementing the “Double.compare()” method in Java.

What is the “Double.compare()” Method in Java?

The “compare()” is a static method of the “Double” class that is utilized to compare the two double values.

Syntax

In the above syntax, “double a” and “double b” correspond to the double values that need to be compared with each other based on the following parameters of “compare()” method:

Returned Value Comparison Outcome
0 If both the values are the same.
-1 If the former value, i.e., “a” is less than the latter value, i.e., “b”.
1 If the former value is greater than the latter value.

Example 1: Applying the “Double.compare()” Method in Java to Compare the Specified Double Values

In this example, the “Double.compare()” method can be applied to compare the specified two double values:

According to the above code snippet, apply the following steps:

  • Initialize the two provided double values.
  • After that, apply the “compare()” method accumulating the initialized values differently as its argument.
  • Here, all the possible outcomes, i.e., “return values” are covered at each step.
  • Lastly, display the returned values based on the applied comparison.

Output

In this output, it can be observed that the corresponding outcome is generated based on the applied comparison differently.

Before proceeding to the next example, make sure to include the below-provided package to enable user input:

Example 2: Applying the “Double.compare()” Method in Java to Compare the User Input Double Values

This example compares the user input double values by placing the method’s return value as an exception in the “if/else” statement:

According to this code snippet, apply the following steps:

  • First of all, create a “Scanner” object using the “new” keyword and the “Scanner()” constructor, respectively.
  • The “in” parameter reads the input and the “nextDouble()” method takes the user input as double.
  • Now, apply the “compare()” method considering each of the returned values, i.e., “0”, “1”, and “-1”, respectively using the “if/else” statement.
  • Lastly, log the corresponding message with respect to the invoked condition.

Output

In this output, it can be seen that each of the conditions is invoked based on the compared user input double values.

Example 3: Applying the “Double.compare()” Method in Java to Compare the Double Objects

In this example, the discussed method can be implemented to compare the double objects:

In this example, create two “double” objects via the “new” keyword and the “Double()” constructor, respectively comprising the stated double values. After that, likewise, compare the created objects with the help of the “Double.compare()” method and log the corresponding outcome.

Output

In this outcome, it can be implied that the double values are compared accordingly.

Conclusion

The “compare()” is a static method of the “Double” class in Java which is utilized to compare the two double values and returns the values instead based on the applied comparison. This method can be utilized to compare the specified, user input double values, or the double objects. This blog is guided to utilize the “Double.compare()” method in Java.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

# Java Floating Point Operations

Floating-point numbers are numbers that have fractional parts (usually expressed with a decimal point). In Java, there is two primitive types for floating-point numbers which are float (uses 4 bytes), and double (uses 8 bytes). This documentation page is for detailing with examples operations that can be done on floating points in Java.

# Comparing floating point values

You should be careful when comparing floating-point values ( float or double ) using relational operators: == , != , < and so on. These operators give results according to the binary representations of the floating point values. For example:

The calculation oneThird has introduced a tiny rounding error, and when we multiply oneThird by 3 we get a result that is slightly different to 1.0 .

This problem of inexact representations is more stark when we attempt to mix double and float in calculations. For example:

The floating point representations used in Java for the float and double types have limited number of digits of precision. For the float type, the precision is 23 binary digits or about 8 decimal digits. For the double type, it is 52 bits or about 15 decimal digits. On top of that, some arithmetical operations will introduce rounding errors. Therefore, when a program compares floating point values, it standard practice to define an acceptable delta for the comparison. If the difference between the two numbers is less than the delta, they are deemed to be equal. For example

Delta compare example:

Also for comparison of double and float primitive types static compare method of corresponding boxing type can be used. For example:

Finally, determining what deltas are most appropriate for a comparison can be tricky. A commonly used approach is to pick delta values that are our intuition says are about right. However, if you know scale and (true) accuracy of the input values, and the calculations performed, it may be possible to come up with mathematically sound bounds on the accuracy of the results, and hence for the deltas. (There is a formal branch of Mathematics known as Numerical Analysis that used to be taught to computational scientists that covered this kind of analysis.)

# OverFlow and UnderFlow

Float data type

The float data type is a single-precision 32-bit IEEE 754 floating point.

Maximum possible value is 3.4028235e+38 , When it exceeds this value it produces Infinity

Float UnderFlow

Minimum value is 1.4e-45f, when is goes below this value it produces 0.0

double data type

The double data type is a double-precision 64-bit IEEE 754 floating point.

Double OverFlow

Maximum possible value is 1.7976931348623157e+308 , When it exceeds this value it produces Infinity

Double UnderFlow

Minimum value is 4.9e-324, when is goes below this value it produces 0.0

# Formatting the floating point values

Floating point Numbers can be formatted as a decimal number using String.format with ‘f’ flag

Floating point Numbers can be formatted as a decimal number using DecimalFormat

# Strict Adherence to the IEEE Specification

By default, floating point operations on float and double do not strictly adhere to the rules of the IEEE 754 specification. An expression is allowed to use implementation-specific extensions to the range of these values; essentially allowing them to be more accurate than required.

strictfp disables this behavior. It is applied to a class, interface, or method, and applies to everything contained in it, such as classes, interfaces, methods, constructors, variable initializers, etc. With strictfp , the intermediate values of a floating-point expression must be within the float value set or the double value set. This causes the results of such expressions to be exactly those that the IEEE 754 specification predicts.

All constant expressions are implicitly strict, even if they aren’t inside a strictfp scope.

Therefore, strictfp has the net effect of sometimes making certain corner case computations less accurate, and can also make floating point operations slower (as the CPU is now doing more work to ensure any native extra precision does not affect the result). However, it also causes the results to be exactly the same on all platforms. It is therefore useful in things like scientific programs, where reproducibility is more important than speed.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *