Numpy没有看到相等的浮点数

时间:2016-10-31 23:26:25

标签: python numpy numbers

我有矢量x1和x0

x1=np.array([float number, float number, float number])
x0=np.array([float number, float number, float number])

例如,x1 = [2.5,3.1,0.0],x2 = [0.0,1.0,1.2] 迭代(i)是我的一些迭代。 当(i)小x1!= x2但是当我很大时我们可以看到x1 = x2 我想找到(i)当x1 = x2

例如,i = 20,x1 = [0.42,0.53,0.17],x2 = [0.42,0.53,0.17]你可以看到x1 == x2所以这是我的答案。 i = 20

for i in range(100):
    x1 = iteration(x0)
    print('number iteration=', i, 'x1=', x1, 'x0=', x0)
    if (str(x0[0]) == str(x1[0])) and (str(x0[1]) == str(x1[1])) and    (str(x0[2]) == str(x1[2])):
        print('We solved the problem:')
        break
    x0 = x1
    print(x0)
    print('i=', i, ' our solve: ', x0)

我的问题。我看到我的答案是(i)= 11因为x1 = [0.78561487 0.49584664 0.37006133] x0 = [0.78561487 0.49584664 0.37006133]

当然,x1 == x2,但是Numpy没有看到。 Numpy写道我的答案是(i)= 15 x1 = [0.78561487 0.49584664 0.37006133] x0 = [0.78561487 0.49584664 0.37006133]

为什么会这样?我用字符串来比较我的数字。我怎样才能得到正确答案?我的意思是(i)= 11。

我尝试寻找解决方案 我读过这个:Why can't decimal numbers be represented exactly in binary?

好的,阅读很有意思,但无论如何我不明白如何解决我的问题。

例如, 根(数学)原因是当你处理整数时,它们是无穷无尽的。 这意味着,即使它们数量无限,我们也可以“计算”序列中的所有项目,而不会跳过任何项目。这意味着如果我们想要将项目放在列表中的第610000000000000位置,我们可以通过公式计算出来。 然而,实数无数无限。你不能说“给我6100-0000000000位置的实数”并得到答案。原因是,当您考虑浮点值时,即使在0和1之间,也会有无数个值。任何两个浮点数都是如此。

但是这篇文章对我没有帮助。例如,

input: print(1/3)
output: 0.3333333333333333

我们可以看到非常大的浮点数:0.3333333333333333 但我的浮动数字较短:0.785614865367

我的问题: 我发现数字迭代= 11(i = 11)。但我的程序写道,number_iteration = 15。但谁是对的?也许我的程序知道的更多,这个答案(i = 15)是正确的?我的意思是,如果我这样做,那么我是否会找到正确的答案?我的意思是也许i = 11不是正确的答案而我= 15也不是正确的答案。也许我需要做别的事情

这是我的计划:

import numpy as np
# The goal to my program is to find vector v: f1(v)=0, f2(v)=0, f3(v)=0, v=[x,y,z]
#f1(x,y,z)=x^2+y^2+z^2-1=0
#f2(x,y,z)=2x^2+y^2-4z=0
#f3(x,y,z)=3x^2-4y+z^2=0

def f(v):
 # v is a vector, I calculate f1(v), f2(v) and f3(v).
 #return f1(v), f2(v), f3(v)
 return v[0]**2+v[1]**2+v[2]**2-1, 2*v[0]**2+v[1]**2-4*v[2], 3*v[0]**2-4**v[1]+v[2]**2

#calculate Jacobi matrix
def matr_yakobi(v):
        return np.matrix([[2*v[0], 2*v[1], 2*v[2]], [4*v[0], 2*v[1], -4], [6*v[0], -8*v[1], 2*v[2]]])

def iteration(x0):
    #x0 is a vector, my goal is to return vector x2, that will more close   to solve equations f1(x2)=0, f2(x2)=0, f3(x2)=0,
    #My last x2 will solve these equations
    fx0 = np.array(f(x0))
    fxot = fx0[np.newaxis]

    Yakobi = matr_yakobi(x0)
    det = np.linalg.det(Yakobi)
    if det == 0.0:
        print('DET=0, ERROR')
    Yakobi_inverse = Yakobi.I

    x1 = x0.T - (Yakobi_inverse * fxot.T).T
    x2 = np.array([x1[0, 0], x1[0, 1], x1[0, 2]])

    return x2

x0 = np.array([0.5, 0.5, 0.5], dtype='float')
print(x0)

for i in range(100):
    x1 = iteration(x0)
    print('number iteration=', i, 'x1=', x1, 'x0=', x0)
    if (str(x0[0]) == str(x1[0])) and (str(x0[1]) == str(x1[1])) and (str(x0[2]) == str(x1[2])):
        print('We solved the problem:')
        break
    x0 = x1
    print(x0)
print('i=', i, ' our solve: ', x0)

0 个答案:

没有答案