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

后端 未结 3 867
感动是毒
感动是毒 2021-01-17 09:21
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

3条回答
  •  悲哀的现实
    2021-01-17 09:56

    (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).

提交回复
热议问题