0

why Math.log(n) / Math.log(3) is not always equal to Math.log10(n) / Math.log10(3), There's a fractional difference. Is it due type that is return by Math.log or it's calculation flaw in the library?

Code:

System.out.println("Math.log10(243) / Math.log10(3) = " + Math.log10(243) / Math.log10(3));
System.out.println("Math.log(243) / Math.log(3) = " + Math.log(243) / Math.log(3));

System.out.println("Math.log10(19683) / Math.log10(3) = " + Math.log10(19683) / Math.log10(3));
System.out.println("Math.log(19683) / Math.log(3) = " + Math.log(19683) / Math.log(3));

System.out.println("Math.log10(59049) / Math.log10(3) = " + Math.log10(59049) / Math.log10(3));
System.out.println("Math.log(59049) / Math.log(3) = " + Math.log(59049) / Math.log(3));

System.out.println("Math.log10(1594322) / Math.log10(3) = " + Math.log10(1594322) / Math.log10(3));
System.out.println("Math.log(1594322) / Math.log(3) = " + Math.log(1594322) / Math.log(3));

Output

Math.log10(243) / Math.log10(3) = 5.0
Math.log(243) / Math.log(3) = 4.999999999999999
Math.log10(19683) / Math.log10(3) = 9.0
Math.log(19683) / Math.log(3) = 9.0
Math.log10(59049) / Math.log10(3) = 10.0
Math.log(59049) / Math.log(3) = 9.999999999999998
Math.log10(1594322) / Math.log10(3) = 12.999999429074592
Math.log(1594322) / Math.log(3) = 12.99999942907459
Sadiq Khoja
  • 522
  • 1
  • 5
  • 23
  • It's because floating-point math is not infinitely precise. You're working with approximations of fractions, not with actual ratios. – Federico klez Culloca Dec 13 '21 at 14:55
  • are you aware of the limitations of floating point arithmetics? – njzk2 Dec 13 '21 at 14:56
  • In cases like this I decide on a desired degree of accuracy and then round accordingly. Or you could find a `BigDecimal` package that implements transcendental functions. I found [logarithm-of-a-bigdecimal](https://stackoverflow.com/questions/739532/logarithm-of-a-bigdecimal) on this site. But doubles only have 53 bits of precision to work with. – WJS Dec 13 '21 at 16:14

0 Answers0