Sunday 21 December 2014

Precision in Floating Point Numbers in Java

A float is a single-precision floating-point number. A double is a double-precision floating-point number. I read somewhere that computers cannot store floating-point numbers precisely so I checked this out myself in program prog51:

andrew@UBUNTU:~/Java$ cat prog51.java
public class prog51
{
public static void main (String args[])
  {
  float f1 = 81.3f * 1.94f;
  System.out.println ("f1 = " + f1);
  double d1 = 81.3d * 1.94d;
  System.out.println ("d1 = " + d1);
  }
}
andrew@UBUNTU:~/Java$ javac prog51.java
andrew@UBUNTU:~/Java$ java prog51
f1 = 157.72202
d1 = 157.72199999999998
andrew@UBUNTU:~/Java$


Judging by this, neither of these data types would be suitable for applications where accuracy is important such as the production of bank statements. The only way I found to calculate the correct answer to the multiplication sum above was as shown in prog52:

andrew@UBUNTU:~/Java$ cat prog52.java
public class prog52
{
public static void main (String args[])
  {
  float f1 = 813f * 194f / 1000f;
  System.out.println ("f1 = " + f1);
  double d1 = 813d * 194d / 1000d;
  System.out.println ("d1 = " + d1);
  }
}
andrew@UBUNTU:~/Java$ javac prog52.java
andrew@UBUNTU:~/Java$ java prog52
f1 = 157.722
d1 = 157.722
andrew@UBUNTU:~/Java$


When I find a better way, I will let you know.