Presentation

This blog is developed by the testing team of the Alarcos Research Group (Institute of Technologies and Information Systems, Instituto de Tecnologías y Sistemas de Información, Universidad de Castilla-La Mancha, Spain). In the testing team, we mainly work on the automation of the software testing process. We deal with:

-Mutation testing.

-Model-based testing.

-Testing in Software Product Lines.

-Testing of Information Systems.

-Combinatorial testing.

Friday, February 17, 2012

The Java precision...

Hi all,

The other day i was testing a system that calcuates weights and i discobered a precision bug in Java.

Try to run this:

public void testPor3(){
double a = 3;
double b = a * 0.2;
System.out.println(b);
double af = 3;
double bf = a / 5;
System.out.println(bf);
}

The output that i got was:

0.6000000000000001
0.6


Then, i and Fede googled about this error and we found this (http://www.velocityreviews.com/forums/t139008-java-double-precision.html):

double val = 0;
for(int i=0;i<10;i++) {
val+=0.1;
System.out.println(val);
}

has the following (terrible) output:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999


What a mess!

3 comments:

  1. By the way, If someone knows how to solve this precision problem, please let me know, because I need to calculate weights with this precision...

    ReplyDelete
  2. That's a natural result from using IEEE 754 floating point numbers. Basically, some decimal fractions cannot be exactly represented using binary fractions. It's like trying to represent 1/3: it'd be "0,333..." in base 10, but only "0,1" in base 3 (1*3^{-1}).

    If you're that concerned about getting exact results, use BigDecimal instead of a regular float. BigDecimal guarantees that things like 0.1 + 0.1 really produce 0.2 and not 0.19999 or 0.200001.

    ReplyDelete
  3. Here's an example. Try running it :-).

    http://pastebin.com/59c22AdZ

    ReplyDelete