整数数组与浮点数组上带有**的numpy幂运算

时间:2020-05-21 00:14:20

标签: python arrays numpy precision exponentiation

为什么对在浮点数组和整数数组上进行操作的import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String text = "some text then https://myhost.ab.us2.myDomain.com " + "and then some more text some text then " + "myhost.ab.us2.myDomain.com and then some more text"; String pat = "\\b(?:https?://)?(\\w+)\\.(?:\\w+\\.)*myDomain\\.com"; Matcher matcher = Pattern.compile(pat).matcher(text); while (matcher.find()) { System.out.println(matcher.group(1)); // => myhost myhost } } } 有区别?

  1. **在整数数组上与在浮点数组上有何不同?
  2. 这是机器精度的舍入问题吗?
  3. 为什么只有一个数组问题而不是我键入它的问题?

MWE:为什么**不等于f(ns)

f(fs)

导致

import numpy as np
def f(x):
    a = +x**5
    b = +x**6 
    return a-b

ns = np.array([60])   #integers
fs = np.array([60.])  #floats

print(ns)
print(fs)

print(f(ns))
print(f(fs))

print(int(60)**5- int(60)**6)
print(60.**5 - 60.**6)

2 个答案:

答案 0 :(得分:2)

因为np.int32int是不同的东西。换句话说,numpy整数数组的元素不是Python整数。

在Python中,int是任意长度的整数。您可以计算123**45并获得90位数以上的整数,即正好123**45

在numpy中,数组元素是标准的32位或64位(有时是8或16位)整数,而算术运算符是标准CPU算术。在这种情况下,几乎可以肯定数字是带符号的或无符号的32位。因此,它使用32位整数计算60**6。由于不适合32位,因此结果类似于60 6 模2 32

答案 1 :(得分:1)

您的系统默认将int类型设置为np.int32,因此这是一个溢出问题。您需要使用np.int64才能正常工作。观察:

In [3]: ns = np.array([60],dtype=np.int32)

In [4]: f(ns)
Out[4]: array([1366240256], dtype=int32)

In [5]: ns = np.array([60],dtype=np.int64)

In [6]: f(ns)
Out[6]: array([-45878400000])