Floating point operation can be used directly to add and subtract operations using the + and - operators, but there may be certain problems:
- Precision issues
- Comparative Questions
- Cumulative Error
1. Comparison of size
Comparison question: Due to precision issues, it may be an error to directly compare whether two floating point numbers are equal.
1.1 Use the compareTo() method
For Double wrapper classes, you can use the compareTo() method to compare the sizes of two Double objects.
This method also returns an integer representing the result of the comparison
Double a = 0.1 + 0.2; Double b = 0.3; int result = (b); if (result < 0) { ("a is less than b"); } else if (result > 0) { ("a is greater than b"); } else { ("a is equal to b"); }
1.2 Comparison using tolerance values (Epsilon)
double a = 0.1 + 0.2; double b = 0.3; double epsilon = 0.000001; // Tolerance value if ((a - b) < epsilon) { ("a and b are approximately equal"); } else if (a < b) { ("a is less than b"); } else { ("a is greater than b"); }
1.3 Use ()
The () method is a static method that can be used to compare two double values.
This method returns an integer indicating the relationship between the first value and the second value:
- If the first value is less than the second value, a negative number is returned.
- If the first value is equal to the second value, zero is returned.
- If the first value is greater than the second value, a positive number is returned.
double a = 0.1 + 0.2; double b = 0.3; int result = (a, b); if (result < 0) { ("a is less than b"); } else if (result > 0) { ("a is greater than b"); } else { ("a is equal to b"); }
2. Sum operation
- Precision problem: Floating point numbers are stored in computers as approximate values, so there may be accuracy loss when performing addition and subtraction operations.
- Cumulative error: When performing multiple floating-point operations, the error may accumulate, resulting in greater deviations in the result.
2.1 Use BigDecimal to accurately sum
// Create BigDecimal objectBigDecimal num1 = new BigDecimal("0.1"); BigDecimal num2 = new BigDecimal("0.2"); // Accurate sumBigDecimal sum = (num2); ()
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.