Python可能舍入错误?

除数0

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

user2357112支持Monica
np.array(x, y)

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

np.array([x, y])

现在,你实际上传递ydtype参数。我不确定这不是引发错误的错误TypeError无论如何,您实际上都将获得一个0维数组(是,0),其唯一元素是x,并且广播规则意味着:

temp1 = np.subtract(temp1, otherArr)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章