1

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

David Bremmen
  • 75
  • 1
  • 9
  • 1
    Not a bug, that's just how floating-point math works when you exceed the precision it can handle. The correct answer is 1.551121004333098**5984**E25, which can be calculated using `BigInteger`. – Andreas May 10 '20 at 04:37
  • Thanks for the response! But why if I'm multiplying the same numbers in one direction it gives the correct answer and in the other not? As I'm working with the same numbers the multiplication operation shouldn't be idempotent for the same number set? – David Bremmen May 10 '20 at 04:41
  • 2
    Because cumulative rounding errors are different depending on the order you multiply the values. See [first link](https://stackoverflow.com/q/11829433/5221149) up top. – Andreas May 10 '20 at 04:48
  • You've just illuminated me. Thanks a lot! – David Bremmen May 10 '20 at 04:57

0 Answers0