Reputation: 78
I'm having a small issue, I have some code that calculates a mean value from a given set of data, I do this from several different computers (some with linux, some with windows, some 32bits and others 64bits), but when I watch the database results the some values that should be equal are slightly different.
This makes no difference for my program but I was wondering why it was this way, I was under the impression that floating point operations with the same word lenght should yield the same result (I was obviously wrong).
This is a small sample code that I wrote to check:
public class Test{
public static void main(String... args){
double counter = 0, value = 1./10;
for (int i = 0; i < 1000000; i++){
counter += value;
}
System.out.println(counter);
}
}
It basically calculates 1000000 / 10, I know that the result won't be exact but in some pcs it prints a number that is slightly less than 100000 and in other cases it prints a number slightly greater.
Upvotes: 1
Views: 154
Reputation: 1357
If you really need the same error on all the platforms you should use the strictfp
keyword in your method declaration, check out the selected answer on this post: When should I use the "strictfp" keyword in java?
Let it be noted that strictfp
only works on your current block, and does not propagates though the code, so if you are calling some methods in the middle they should have strictfp
too (also you should use StrictMath
instead of Math
).
At any rate if this is not affecting your code, just let it be... strict floating point operations have a higher computational cost that regular floating point operations.
Upvotes: 5
Reputation: 6148
Different plate forms have different ways to represent floating point.
To get same results you should limit the precision to a specific number of decimal places.
Upvotes: 1
Reputation: 28812
I would think it depends on compiler optimization techniques used. E.g. with no optimizations, you get a lot of addition, resulting in probably loss of precision, with a compiler that can understand the operations involved, the whole loop might be replaced with counter = value*1000000
The precision of double
and its operations are set precisely in the language
Upvotes: 2