Python 可能的舍入错误?

Python 可能的舍入错误?,python,numpy,rounding,Python,Numpy,Rounding,我有一段代码,给定一些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

我有一段代码,给定一些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)
这不是创建两元素数组的方式。您需要将单个类似数组的参数传递给
数组
,而不是单个元素:

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

temp1 = np.subtract(temp1, otherArr)

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

numpy.array(x,y)
应引发
TypeError:数据类型不清楚
。您发布的代码似乎与实际运行的代码不匹配。你能发布一个吗?你发布的输出似乎表明,在你的真实代码中,你做了类似于
temp1=numpy.array([x,x])
,混淆了
x
y
@user2357112的事情。我添加了一个应该立即运行的MCVE,哇,太蠢了。考虑到我的python初学者技能以及我所做的一切,我认为如果我做错了,编译器会抓住它,但这是一个糟糕的假设。谢谢