Python 可能存在舍入误差?

Python Possible Rounding Errors?

我有这段代码,给定一些 x 和 y 浮点数,我必须将它们减去另一个浮点数并将它们放入 numpy 数组的前两个索引中。我要减去的浮点数已经在一个 numpy 数组中给出。但是,我 运行 遇到了一个奇怪的问题,即单独减去索引会产生与减去 numpy 数组不同的答案。这是代码:

import numpy as np

def calcFunc(x, y):
    array = np.zeros(2)
    print ("X is", x, "otherArr[0] is", otherArr[0])
    print ("Y is", y, "otherArr[1] is", otherArr[1])
    array[0] = x - otherArr[0]
    array[1] = y - otherArr[1]
    temp1 = np.array(x, y)
    temp1 = np.subtract(temp1, otherArr)
    print("temp1 is" , temp1)
    print("sub is", array)

x = np.linspace(-3, 3, 50)
y = np.linspace(-3, 3, 50)

otherArr = np.random.rand(2) * 0.25
for i in range(len(x)):
    for j in range(len(y)):
        calcFunc(x[i], y[j])

其中 x 和 y 是我从其他地方得到的一些浮点数,并传递给这个做这个减法的函数,所以它会改变每次迭代。那么代码输出为:

X is -3.0 otherArr[0] is 0.129294357724
Y is -3.0 otherArr[1] is 0.0308568538399
temp1 is [-3.12929436 -3.03085685]
array is [-3.12929436 -3.03085685]
X is -3.0 otherArr[0] is 0.129294357724
Y is -2.87755102041 otherArr[1] is 0.0308568538399
temp1 is [-3.12929436 -3.03085685]
array is [-3.12929436 -2.90840787]
X is -3.0 otherArr[0] is 0.129294357724
Y is -2.75510204082 otherArr[1] is 0.0308568538399
temp1 is [-3.12929436 -3.03085685]
array is [-3.12929436 -2.78595889]
X is -3.0 otherArr[0] is 0.129294357724
Y is -2.63265306122 otherArr[1] is 0.0308568538399
temp1 is [-3.12929436 -3.03085685]
array is [-3.12929436 -2.66350992]
X is -3.0 otherArr[0] is 0.129294357724
Y is -2.51020408163 otherArr[1] is 0.0308568538399
temp1 is [-3.12929436 -3.03085685]
array is [-3.12929436 -2.54106094]
X is -3.0 otherArr[0] is 0.129294357724
Y is -2.38775510204 otherArr[1] is 0.0308568538399
temp1 is [-3.12929436 -3.03085685]
array is [-3.12929436 -2.41861196]

我假设这与 Y 在第一次迭代后有更多小数点有关,并且出现某种舍入错误。但是,为什么结果不同于简单地减去指数呢?这不是数组减法首先要做的吗?

np.array(x, y)

这不是创建二元素数组的方式。您需要将单个类似数组的参数传递给 array,而不是单个元素:

np.array([x, y])

现在,您实际上是将 y 作为 dtype 参数传递。我不确定这不会引发 TypeError 是否是错误。在任何情况下,您实际上得到一个 0 维数组(是的,0),其唯一元素是 x,广播规则意味着:

temp1 = np.subtract(temp1, otherArr)

产生 np.array([x-otherArr[0], x-otherArr[1]]).