[issue34645] math and numpy yield different results (nan)

Steven D'Aprano report at bugs.python.org
Wed Sep 12 12:10:12 EDT 2018


Steven D'Aprano <steve+python at pearwood.info> added the comment:

Your code gives runtime warnings of invalid values. You should fix that. If your values are invalid, there's probably a bug in your code.

RuntimeWarning: invalid value encountered in double_scalars

Your code is also very complex. You ought to simplify the example so that it is easier to understand, all the business with linspace and duplicated code just adds complexity and makes it hard to understand.

I simplified your code to this:

import numpy as np
n=2.758
n2 = 2.0 / n
ct = np.cos(2 * np.pi * 2.0 / 5)
print("numpy", ct, abs(ct ** n2) * 5.0)


which gives this output:

__main__:1: RuntimeWarning: invalid value encountered in double_scalars
('numpy', -0.80901699437494734, nan)

So there's a problem. You're trying to raise a negative number to a positive value, and numpy doesn't like it and returns a NAN.

But using the standard math library, raising a negative number to a positive value gives you a complex number:

ct = math.cos(2 * math.pi * 2.0 / 5)
print(ct**n2)
print("math", ct, abs(ct ** n2) * 5.0)


which gives this output:

(-0.5572617094280153+0.6517928032447587j)
math -0.8090169943749473 4.287698890886272

So the behaviour is correct and this is not a bug in either math nor numpy. They're just doing different things.

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34645>
_______________________________________


More information about the Python-bugs-list mailing list