This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Division using math.pow and math.log approximation fails
Type: behavior Stage: resolved
Components: Library (Lib) Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Marcelo Marotta, mark.dickinson, rhettinger
Priority: normal Keywords:

Created on 2019-02-20 18:04 by Marcelo Marotta, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg336132 - (view) Author: Marcelo Marotta (Marcelo Marotta) Date: 2019-02-20 18:04
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
msg336135 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2019-02-20 18:23
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)`.
History
Date User Action Args
2022-04-11 14:59:11adminsetgithub: 80236
2019-02-20 18:23:19mark.dickinsonsetstatus: open -> closed
resolution: not a bug
messages: + msg336135

stage: resolved
2019-02-20 18:14:49xtreaksetnosy: + rhettinger, mark.dickinson
2019-02-20 18:04:41Marcelo Marottacreate