Why does numpy.power return 0 for small metrics, and math.pow returns the correct answer?

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

I expect both teams to return 1e-100. This is also not a problem, since the problem persists even after increasing the accuracy to 500. Is there any setting that I can change to get the correct answer?

+51
python numpy exponentiation
Apr 09 '14 at 7:52
source share
3 answers

Oh, this is much "worse" than this:

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

But this is a hint of what is happening: 10 is an integer, and numpy.power does not force the numbers to float. But it 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 ** converted to float:

 In [5]: 10**-1 Out[5]: 0.1 
+70
Apr 09 '14 at 7:57
source share

The numpy method assumes that you want the integer to be returned from the moment you enter the integer.

 np.power(10.0,-100) 

works as you expected.

+35
Apr 09 '14 at 7:57
source share

(Only a note to the two other answers on this page.)

To enter two input values, you can check the data type of the object that np.power will return by checking 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 the l characters compatible with the Python d () boards.

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

So, given 10 and -100, np.power match the signature integer integer -> integer and return the integer 0 .

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

+2
Feb 04 '15 at 21:31
source share



All Articles