Floating point accuracy

Question:
When I do the following,

double answer = 121 * .1;System.out.println("Answer: " + answer);

I get,

Answer: 12.100000000000001

What’s going on?

Answer:
Almost every computer architecture represents numbers in binary format, also known as base 2. Java’s virtual machine is no exception and follows the IEEE binary floating point standard. It is not possible to represent exactly all floating point numbers in base 2 (or base 10, for that matter). The base 10 decimal number 0.1 is one such number. You should assume that every floating point operation will contain some small error and account for it by comparing numbers witha tolerance value representing the amount of error you are willing to accept.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: