英文:
Wierd behavior with raising intgers to the negative powers in python
问题
我注意到在使用np.array
将整数取负幂时出现了奇怪的行为。具体来说,我正在执行以下操作:
import numpy as np
a = 10**(np.arange(-1, -8, -1))
结果出现以下错误。
ValueError: 不允许整数取负整数次幂。
这很奇怪,因为代码10**(-1)
正常工作。然而,以下的解决方法(其中10
是浮点数而不是整数)正常工作。
import numpy as np
a = 10.**(np.arange(-1, -8, -1))
print(a) # 打印数组([1.e-01, 1.e-02, 1.e-03, 1.e-04, 1.e-05, 1.e-06, 1.e-07])
为什么对整数不有效?欢迎任何解释。
英文:
I am observing this weird behavior when I am raising an integer to the negative power using an np.array
. Specifically, I am doing
import numpy as np
a = 10**(np.arange(-1, -8, -1))
and it results in the following error.
>ValueError: Integers to negative integer powers are not allowed.
This is strange as the code 10**(-1)
works fine. However the following workaround (where 10
is a float instead of integer) works fine.
import numpy as np
a = 10.**(np.arange(-1, -8, -1)
print(a) # Prints array([1.e-01, 1.e-02, 1.e-03, 1.e-04, 1.e-05, 1.e-06, 1.e-07])
Why is it not valid for integers? Any explanation is appreciated.
答案1
得分: 2
这是因为输入的10是一个整数。
10**(np.arange(-1, -8, -1))
numpy.arange()
被设计成必须要给出整数或什么都不给出,因为输入是整数。
相反地;
a = 10.**(np.arange(-1, -8, -1))
幸运地,它给出了结果,因为10.0是一个浮点数。
编辑: 找到了一个支持我的观点的答案;为一个重复问题投了票:
https://stackoverflow.com/questions/43287311/why-cant-i-raise-to-a-negative-power-in-numpy
英文:
This is happening because the input 10 is an integer.
10**(np.arange(-1, -8, -1))
numpy.arange()
is designed such a way that that has to give 10**(np.arange(-1, -8, -1))
integers or nothing since input is an integer.
On the contrary;
a = 10.**(np.arange(-1, -8, -1)
gives results happily as 10.0
is a float
Edit: found an answer to back my point; voted for a duplicate:
https://stackoverflow.com/questions/43287311/why-cant-i-raise-to-a-negative-power-in-numpy
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论