【问题标题】:Test of equality between arrays using in1d function使用 in1d 函数测试数组之间的相等性
【发布时间】:2016-01-03 15:21:01
【问题描述】:

在我提出问题之前,我先向您提供代码。

代码

from scipy import *
x = randn(10)
cum_x = cumsum(x)
#The objective is to recover x using cum_x and the diff function.
y = append(cum_x[0],diff(cum_x))
#Now, y should be equal to x but this is not confirmed by the function in1d
test = in1d(x,y)

即使 y 和 x 明显相同,变量 test 也不会返回“True”布尔值数组。这里有什么问题?

提前谢谢你。

【问题讨论】:

  • 我想有浮点问题,allclose 可能是你想要的
  • 是的。但为什么 in1d 不返回 True 值数组?为什么要四舍五入?您认为累积和和差异会产生稍微不同的浮点数吗?
  • 我添加了一个显示精度提高的答案,您可以看到有细微差别
  • 除此之外:即使 xy 没有明显不同,in1d 也不是检查它们是否相等的好方法: -- in1d([1,2],[2,1]) 给出毕竟都是真的。

标签: python arrays scipy


【解决方案1】:

如果您使用set_printoptions 来提高精度,您会发现一些差异:

from scipy import *
set_printoptions(30)
x = randn(10)
cum_x = cumsum(x)

#The objective is to recover x using cum_x and the diff function.
y = append(cum_x[0], diff(cum_x))
print(x)
print("\n")
print(y)
#Now, y should be equal to x but this is not confirmed by the function in1d
test = in1d(x, y)
print(test)

输出:

[ 0.54816314147543721002620031868   0.14319052613251953554041051575
  0.489110961092741158839913850898 -0.093011827554544138085823590245
 -0.58370623188476589149331630324  -0.40395493550429123486011917521
  0.387387395892057895263604905267  1.001637373359834937147638811439
 -1.486778459872974744726548124163  1.446772274227251076084144187917]


[ 0.54816314147543721002620031868   0.143190526132519591051561747008
  0.48911096109274110332876261964  -0.093011827554544179719187013688
 -0.58370623188476589149331630324  -0.40395493550429123486011917521
  0.387387395892057895263604905267  1.001637373359834937147638811439
 -1.486778459872974744726548124163  1.446772274227251076084144187917]
[ True False False False  True  True  True  True  True  True]

您可能想要的是 allclose,但有趣的是,在我的 ubuntu 系统上将 dtype 设置为 np.float128np.longdouble 不会丢失精度并且 in1d 返回 True。

 cum_x = cumsum(x,dtype=np.longdouble)

【讨论】:

  • 那么你认为累积和和差分函数会产生这些细微的差异吗?
  • @Charlie,如果你看看他们肯定做的输出,你想使用的是allclose
猜你喜欢
  • 1970-01-01
  • 2015-01-28
  • 2018-01-20
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2011-04-17
  • 1970-01-01
相关资源
最近更新 更多