Rounding off errors in Java

In the given tutorial, we are going to learn how to round off errors in Java.

In Java, most programs store the result of integer computations in 32 or 64 bits. Several calculations with real numbers outcomes with quantities that are impossible to represent using this number of bits. Because of this, the result of the floating point calculation must be rounded off to fit into it’s finite representation.
We need to take care of round off errors in programming language while handling calculations in floating point numbers. To rectify this round off errors :

  • We can use numerically stable algorithms and we can truncate the digits of which we are not sure that they are correct.
  • We can use java.math.BigDecimal class, which is designed to give us accuracy especially in the case of big fractional numbers.
  • We can use the java.lang.Math.round() method to round off the errors.

java.lang.Math.round() :

  • The java.lang.Math.round()is a built-in math function which is used to round a number to it’s closest integer.
  • This function can be used to minimize any effects of floating point arithmetic storage inaccuracy.
  • The user will be able to round off numbers to the number of decimal places which are needed for the calculation.

Program :

Let’s see a program that shows how the error can be removed :

package java;

public class Demo
{
 public static void main(String[] args)
 {
  double a = 2.99;
  double b = 4.00;

  double c = a*b;

  double d = 5.02;

  //Without rounding off errors
  System.out.println("a = "+(a/2.0));
  //Rounding off errors
  System.out.println("a = "+(Math.round(a)/2.0));

  //Without rounding off errors
  System.out.println("c = "+c);
  //Rounding off errors
  System.out.println("c = "+Math.round(c));

  //Without rounding off errors
  System.out.println("d = "+d);
  //Rounding off errors
  System.out.println("d = "+Math.round(d));

 }
}

Output :

Output of the above program will be :

a = 1.495
a = 1.5
c = 11.96
c = 12
d = 5.02
d = 5

We can see that how we rounded off the errors using Math.round() function.

Leave a Reply