【发布时间】:2014-05-22 06:38:37
【问题描述】:
In [25]: np.power(10,-100)
Out[25]: 0
In [26]: math.pow(10,-100)
Out[26]: 1e-100
我希望这两个命令都返回 1e-100。这也不是精度问题,因为即使将精度提高到 500 后问题仍然存在。是否可以更改某些设置以获得正确答案?
【问题讨论】:
标签: python numpy exponentiation
In [25]: np.power(10,-100)
Out[25]: 0
In [26]: math.pow(10,-100)
Out[26]: 1e-100
我希望这两个命令都返回 1e-100。这也不是精度问题,因为即使将精度提高到 500 后问题仍然存在。是否可以更改某些设置以获得正确答案?
【问题讨论】:
标签: python numpy exponentiation
哦,比那更“糟糕”:
In [2]: numpy.power(10,-1)
Out[2]: 0
但这是对正在发生的事情的提示:10 是一个整数,numpy.power 不会将数字强制为浮点数。但这有效:
In [3]: numpy.power(10.,-1)
Out[3]: 0.10000000000000001
In [4]: numpy.power(10.,-100)
Out[4]: 1e-100
但是请注意,幂运算符**,确实转换为浮点数:
In [5]: 10**-1
Out[5]: 0.1
【讨论】:
numpy 方法假定您希望返回整数,因为您提供了一个整数。
np.power(10.0,-100)
如您所愿。
【讨论】:
(只是此页面上其他两个答案的脚注。)
给定两个输入值,您可以通过检查types 属性来检查np.power 将返回的对象的数据类型:
>>> 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 兼容的整数类型用l 表示,兼容的Python 浮点型用d (documents) 表示。
np.power 通过检查传递的参数类型并使用此列表中的第一个匹配签名有效地决定返回什么。
所以给定 10 和 -100,np.power 匹配 integer integer -> integer 签名并返回整数 0。
另一方面,如果其中一个参数是浮点数,则使用the integer argument will also be cast to a float,并使用float float -> float 签名(并返回正确的浮点值)。
【讨论】: