Double errors in Java

Errors with double in Java often arise due to the inherent limitations of floating-point arithmetic, such as precision loss and rounding errors. Here's an example demonstrating some common errors that can occur when working with double in Java:

public class DoubleErrors {
    public static void main(String[] args) {
        // example 1: Precision Loss
        double num1 = 0.1;
        double num2 = 0.2;
        double sum = num1 + num2;
        System.out.println("Sum: " + sum); // output: 0.30000000000000004
        
        // example 2: Rounding Errors
        double num3 = 1.0;
        for (int i = 0; i < 10; i++) {
            num3 -= 0.1;
        }
        System.out.println("Result: " + num3); // output: 0.9999999999999999
        
        // example 3: Comparison Errors

        double value1 = 0.1 + 0.2;
        double value2 = 0.3;
        if (value1 == value2) {
            System.out.println("Equal"); // this block won't execute
        } else {
            System.out.println("Not Equal"); // output: Not Equal
        }
        
        // example 4: NaN (Not a Number)

        double result = Math.sqrt(-1);
        System.out.println("Result: " + result); // output: NaN
        
        // example 5: Infinity

        double infinity = 1.0 / 0.0;
        System.out.println("Infinity: " + infinity); // output: Infinity
    }
}



Explanation of examples.

1. Precision Loss

Due to the binary representation of floating-point numbers, some decimal values cannot be represented precisely, leading to small errors in arithmetic operations.

2. Rounding Errors

Accumulating rounding errors can lead to unexpected results, especially in iterative calculations.

3. Comparison Errors

Comparing floating-point numbers for equality can be problematic due to precision differences. It's often better to use a tolerance threshold for comparison.

4. NaN (Not a Number)

Certain operations, like taking the square root of a negative number, result in NaN.

5. Infinity

Division by zero or other mathematical operations can result in positive or negative infinity.


To mitigate these issues, it's important to be aware of the limitations of floating-point arithmetic and to use appropriate strategies such as rounding, tolerance thresholds for comparisons, and checking for special values like NaN and infinity. Additionally, using BigDecimal for precise decimal arithmetic may be necessary in cases where exact precision is required.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....