Why does numpy.power return 0 for small exponents while math.pow returns the correct answer?

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

In [25]: np.power(10,-100) Out[25]: 0  In [26]: math.pow(10,-100) Out[26]: 1e-100 

I would expect both the commands to return 1e-100. This is not a precision issue either, since the issue persists even after increasing precision to 500. Is there some setting which I can change to get the correct answer?

回答1:

Oh, it's much "worse" than that:

In [2]: numpy.power(10,-1)    Out[2]: 0 

But this is a hint to what's going on: 10 is an integer, and numpy.power doesn't coerce the numbers to floats. But this works:

In [3]: numpy.power(10.,-1) Out[3]: 0.10000000000000001  In [4]: numpy.power(10.,-100) Out[4]: 1e-100 

Note, however, that the power operator, **, does convert to float:

In [5]: 10**-1 Out[5]: 0.1 


回答2:

numpy method assumes you want integer returned since you supplied an integer.

np.power(10.0,-100)  

works as you would expect.



回答3:

(Just a footnote to the two other answers on this page.)

Given input two input values, you can check the datatype of the object that np.power will return by inspecting the types attribute:

>>> np.power.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q',   'QQ->Q', 'ee->e', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] 

Python-compatible integer types are denoted by l, compatible-compatible Python floats by d (documents).

np.power effectively decides what to return by checking the types of the arguments passed and using the first matching signature from this list.

So given 10 and -100, np.power matches the integer integer -> integer signature and returns the integer 0.

On the other hand, if one of the arguments is a float then the integer argument will also be cast to a float, and the float float -> float signature is used (and the correct float value is returned).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!