奇怪的行为:在Python中将整数乘以负幂。

huangapple go评论60阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月2日 13:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定