Python可能有舍入误差吗?

2024-03-28 23:51:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,给定一些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在第一次迭代后有更多的小数有关,并且出现了某种舍入误差。然而,为什么结果不同于简单地减去指数呢?这不是数组减法首先要做的吗?你知道吗


Tags: 代码innumpyforisnp数组array
1条回答
网友
1楼 · 发布于 2024-03-28 23:51:20
np.array(x, y)

这不是创建两元素数组的方法。{}要传递单个数组,而不是像cd1那样传递单个元素:

np.array([x, y])

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

temp1 = np.subtract(temp1, otherArr)

产生np.array([x-otherArr[0], x-otherArr[1]])。你知道吗

相关问题 更多 >