下面的代码将导致执行打印语句:确定两个复数是否相等
import numpy as np
import math
foo = np.array([1/math.sqrt(2), 1/math.sqrt(2)], dtype=np.complex_)
total = complex(0, 0)
one = complex(1, 0)
for f in foo:
total = total + pow(np.abs(f), 2)
if(total != one):
print str(total) + " vs " + str(one)
print "NOT EQUAL"
然而,我的[1/math.sqrt(2), 1/math.sqrt(2)]
导致total
输入为one
:
(1+0j) vs (1+0j) NOT EQUAL
是它将NumPy与Python的复杂类型混合起来有什么用?
尝试'repr(total)'而不是'str(total)' – 2014-08-30 16:25:19
大概这是一个比较浮点数的问题 - 因为复杂类型只是两个浮点数的组合。检查例如这个小指南:http://floating-point-gui.de/errors/comparison/关于如何比较浮点数。同样,试试'2 == sqrt(2)* sqrt(2)'...... – sebastian 2014-08-30 16:25:42