为什么arange和linspace在下面的代码上不会产生相同的结果?
clang -fopenmp -o bla.obj -c bla.c
clang -fopenmp -o bla.exe bla.obj
元素的数量和它们本身的元素显然是相同的。但是:
a = np.arange(12,17,.2, dtype=float)
b = np.linspace(12.,16.8,25, dtype=float)
print(list(a)==list(b))
结果不相等。
我希望输出为'''True''',但实际输出为'''False'''。
答案 0 :(得分:1)
for _a, _b in zip(a, b):
print (_a, _b)
Based on https://docs.python.org/3/tutorial/floatingpoint.html从数据库检索数据, 您可以从结果中看到为什么它不相同,如下所示:
12.0 12.0
12.2 12.2
12.399999999999999 12.4
12.599999999999998 12.6
12.799999999999997 12.8
12.999999999999996 13.0
13.199999999999996 13.2
13.399999999999995 13.4
13.599999999999994 13.6
13.799999999999994 13.8
13.999999999999993 14.0
14.199999999999992 14.200000000000001
14.399999999999991 14.4
14.59999999999999 14.600000000000001
14.79999999999999 14.8
14.99999999999999 15.0
15.199999999999989 15.200000000000001
15.399999999999988 15.4
15.599999999999987 15.600000000000001
15.799999999999986 15.8
15.999999999999986 16.0
16.199999999999985 16.200000000000003
16.399999999999984 16.400000000000002
16.599999999999984 16.6
16.799999999999983 16.8
暂时,我们可以将np.round
用于此问题。
a = np.arange(12,17,.2, dtype=np.float)
a = np.round(a, 1)
b = np.linspace(12.,16.8,25, dtype=np.float)
b = np.round(a, 1)
print (np.array_equal(a,b))
它返回True
。