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.
If you really need the same error on all the platforms you should use the
strictfpkeyword 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
strictfponly works on your current block, and does not propagates though the code, so if you are calling some methods in the middle they should havestrictfptoo (also you should useStrictMathinstead ofMath).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.