Strictfp returns different results on different systems

76 views Asked by At

I'm using the following method on Windows 8 (Intel Atom Z3775):

public static strictfp void main(String args[])
{
    float a = 0.000000002f;
    float b = 90000300000000004f;
    float c = a * b;
    System.out.println(c);
}

which gives me: 1.80000592E8

When running

public strictfp void calculate()
{
    float a = 0.000000002f;
    float b = 90000300000000004f;
    float c = a * b;
    Toast.makeText(getApplicationContext(), c + "", Toast.LENGTH_LONG).show();
}

i get: 1.8000059E8

Why do they differ? Am I using strictfp wrong?

2

There are 2 answers

0
Andy Turner On BEST ANSWER

You have confirmed that printing the hex representation of the floats shows that the values are the same:

String.format("%08x", Float.floatToIntBits(c))

This means that there is a difference in the implementation of how a float is converted to a String.

Notice that the OpenJDK implementation of java.lang.Float.toString(float) invokes a method from sun.misc.FloatingDecimal - i.e. it is a JDK-specific implementation.

You'd need either:

  • To ensure that you always run the code using the same implementation
  • To provide your own implementation which always produces the same result
  • To specify a shorter format, so that the strings are the same to that many decimal places.
3
Adrian Roman On

Well, the displaying method certainly differs...