Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does numpy.power return 0 for small exponents while 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 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?

like image 935
Jishnu Avatar asked Apr 09 '14 07:04

Jishnu


1 Answers

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 
like image 68
Andrew Jaffe Avatar answered Sep 29 '22 18:09

Andrew Jaffe