Issue 36055: Division using math.pow and math.log approximation fails (original) (raw)

Steps to reproduce the error

import math 1/math.log(math.pow(30,0.5),2) == 2/math.log(30,2) True 1/math.log(math.pow(9,0.5),2) == 2/math.log(9,2) True 1/math.log(math.pow(15,0.5),2) == 2/math.log(15,2) True 1/math.log(math.pow(8,0.5),2) == 2/math.log(8,2) False 2/math.log(8,2) 0.6666666666666666 1/math.log(math.pow(8,0.5),2) 0.6666666666666665

I reproduced the error in Python : Python 3.5.3 and Python 2.7.13

This isn't a bug: floating-point arithmetic is by its nature approximate, and two sequences of operations that would mathematically give the same result need not give the same result with floating-point.

I'd recommend a read of this portion of the tutorial, which goes into some of the issues involved: https://docs.python.org/3/tutorial/floatingpoint.html

Having said that, you'll get slightly better accuracy in general (one can't make specific guarantees, since everything's dependent on the platform's math library) if you use math.sqrt(x) instead of math.pow(x, 0.5), and math.log2(y) instead of math.log(y, 2).