[issue15438] Incredible issue in math.pow

Mark Dickinson report at bugs.python.org
Thu Jul 26 14:56:19 CEST 2012


Mark Dickinson <dickinsm at gmail.com> added the comment:

- I can't find any reason in using math.pow if I can get errors like the one explained.

Yep---don't use math.pow if you want *exact* integer results.  If you're doing numerical calculations and errors of around 1 part in 1 thousand million million are acceptable to you, then math.pow works just fine.  Just like the other math functions (math.log, math.exp, math.sin, etc.), it's using floating-point arithmetic, so converts its inputs to float and gives a float result.  Unlike Python ints, which have unbounded precision, Python floats have a fixed size (64 bits), so there are only finitely many values (less than 2**64) that can be represented exactly.  The fact is that the number you were expecting, 21611482313284249, isn't one of those numbers:  it *doesn't exist* as a float, because it's not exactly representable in the usual 64-bit floating-point type that Python uses internally.

- I've used math.h in my C++ code without having experienced any problem in that pow operation.

I'd be quite surprised if this were true:  if you're using the double type with C or C++, and the pow function from math.h / cmath, you should expect to see *exactly* the same issues.  With the 'long double' type, you may get a little more precision (depending on the platform), but that just delays the point at which those issues would appear.

By the way, don't close the issue just yet!  There's still ongoing discussion here about whether
there's potential for a documentation improvement.

----------
status: closed -> open

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15438>
_______________________________________


More information about the Python-bugs-list mailing list