Floating Point Rounding Off Error
Compacting many infinite real numbers into a finite number of bits requires an approximate representation. Most programs store the result of integer computations 32 or 64 bits max. Given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is a characteristic feature of floating-point computation.
Therefore, while handling calculations in floating point numbers, (especially if calculations are in term of money), we need to take care of round off errors in a programming language.
Below the Example Code.
public
class
Main {
public
static
void
main(String[] args)
{
double
a = 0.7;
double
b = 0.9;
double
x = a + 0.1;
double
y = b - 0.1;
System.out.println("x = "
+ x);
System.out.println("y = "
+ y );
System.out.println(x == y);
}
}

How to rectify round off errors?
- Round the result: The Round() function can be used to minimize any effects of floating point arithmetic storage inaccuracy. The user can round numbers to the number of decimal places that is required by the calculation. For example, while working with currency, you would likely round to 2 decimal places.
- Algorithms and Functions: Use numerically stable algorithms or design your own functions to handle such cases. You can truncate/round digits of which you are not sure they are correct (you can calculate numeric precision of operations too)
- BigDecimal Class: You may use the java.math.BigDecimal class, which is designed to give us accuracy especially in case of big fractional numbers.
- The following program shows how the error can be removed:
public
class
Main {
public
static
void
main(String args[])
{
double
a = 1.0;
double
b = 0.10;
double
x = 9
* b;
a = a - (x);
System.out.println("a = "
+ Math.round(a*1.0)/1.0);
}
}
