devxlogo

Floating point accuracy

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.

See also  5 Tips for Choosing the Right Medical Software for Your Practice
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist