I've found a weird result when calculating the factorial of 25 in Java. If I make the calculation using ascending mode (that is: 1*2*3*4...*25). It gives one result. But if a I do it in descending mode (25*24*23...*1) it gives other result. I'm pasting the code here that I believe is correct and I tried it in many Java compilers (in bold the difference)
- ascending mode: 1.5511210043330986E25
- descending mode: 1.5511210043330984E25
Am I doing something wrong or this can be a bug in the language?
Code
public static void main(String[] args) {
int factorialToCalculate = 25;
double accumulator1 = 1;
double accumulator2 = 1;
for (int i = factorialToCalculate; i>=1; i--) {
accumulator1 = accumulator1 * i;
}
for (int i = 1; i<=factorialToCalculate; i++) {
accumulator2 = accumulator2 * i;
}
System.out.println("Factorial with descending multiplication: " + accumulator1);
System.out.println("Factorial with ascending multiplication: " + accumulator2);
}
To run it in an online compiler you can use this URL: https://www.browxy.com#ALIEN_120955