nan 出现在矩阵的条目中

nan appearing in entries of a matrix

我正在制作一个带有零的 10x10 数组,并让每个条目等于一个足够简单的计算,当我显示我的矩阵时,很多数字前面都有一个 nan,我不确定这是什么意思.这是我的代码:

import numpy as np
%pylab inline
x1=[0.0,0.0,1.0,0.5,2.0,10.0,11.0,12.0,8.0,8.9]
y1=[1.0,1.5,1.0,1.2,2.0,9.0,13.0,8.0,8.0,9.0]
Dis1=np.zeros((10,10))
for i in range(10):
    for j in range(10):
        Dis1[i][j]=sqrt((x1[i]-x1[j])**2-(y1[i]-y1[j])**2)
print(Dis1)

谢谢

我假设,通过阅读你的代码,你得到了每对 x1-y1 之间的距离。所以你应该使用勾股定理,它是 a^2 + b^2 = c^2,而不是 a^2 - b^2 = c^2.

将您的距离计算更改为 Dis1[i][j] = sqrt((x1[i] - x1[j]) ** 2 + (y1[i] - y1[j]) ** 2)

事实上,您正在尝试对潜在负数求平方根,returns NAN。

如果你真的想计算矩阵Dis1,那么你必须使用complex numbers

import numpy as np
x1=[0.0,0.0,1.0,0.5,2.0,10.0,11.0,12.0,8.0,8.9]
x1=np.array(x1, dtype=complex)

y1=[1.0,1.5,1.0,1.2,2.0,9.0,13.0,8.0,8.0,9.0]
y1=np.array(y1, dtype=complex)

Dis1=np.zeros((10,10), dtype=complex)
for i in range(10):
    for j in range(10):
        Dis1[i][j]=sqrt((x1[i]-x1[j])**2-(y1[i]-y1[j])**2)

在您的问题中,每次您尝试计算负数的 sqrt 时,输出都是 nan。对于复数,虚部不为零。

Dis1.imag

array([[ 0.        ,  0.5       , -0.        ,  0.        ,  0.        ,
         0.        ,  4.79583152,  0.        ,  0.        ,  0.        ],
       [ 0.5       ,  0.        , -0.        , -0.        ,  0.        ,
         0.        ,  3.35410197,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  6.63324958,  0.        ,  0.        ,  1.26095202],
       [ 0.        ,  0.        , -0.        ,  0.        ,  0.        ,
         0.        ,  5.38423625,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  6.32455532,  0.        ,  0.        ,  1.17898261],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  3.87298335, -0.        ,  0.        ,  0.        ],
       [ 4.79583152,  3.35410197,  6.63324958,  5.38423625,  6.32455532,
         3.87298335,  0.        , -4.89897949,  4.        ,  3.40440891],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  4.89897949,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  4.        , -0.        ,  0.        ,  0.43588989],
       [ 0.        ,  0.        ,  1.26095202,  0.        ,  1.17898261,
        -0.        ,  3.40440891, -0.        ,  0.43588989,  0.        ]])