具有sum()函数的意外行为

时间:2012-05-07 17:38:04

标签: matlab octave

我正在尝试使用以下代码计算47 x 3规范化设计矩阵X的列总和:

sum(X)

以下是X的内容:

X =

   1.0000e+00   1.3001e-01  -2.2368e-01
   1.0000e+00  -5.0419e-01  -2.2368e-01
   1.0000e+00   5.0248e-01  -2.2368e-01
   1.0000e+00  -7.3572e-01  -1.5378e+00
   1.0000e+00   1.2575e+00   1.0904e+00
   1.0000e+00  -1.9732e-02   1.0904e+00
   1.0000e+00  -5.8724e-01  -2.2368e-01
   1.0000e+00  -7.2188e-01  -2.2368e-01
   1.0000e+00  -7.8102e-01  -2.2368e-01
   1.0000e+00  -6.3757e-01  -2.2368e-01
   1.0000e+00  -7.6357e-02   1.0904e+00
   1.0000e+00  -8.5674e-04  -2.2368e-01
   1.0000e+00  -1.3927e-01  -2.2368e-01
   1.0000e+00   3.1173e+00   2.4045e+00
   1.0000e+00  -9.2196e-01  -2.2368e-01
   1.0000e+00   3.7664e-01   1.0904e+00
   1.0000e+00  -8.5652e-01  -1.5378e+00
   1.0000e+00  -9.6222e-01  -2.2368e-01
   1.0000e+00   7.6547e-01   1.0904e+00
   1.0000e+00   1.2965e+00   1.0904e+00
   1.0000e+00  -2.9405e-01  -2.2368e-01
   1.0000e+00  -1.4179e-01  -1.5378e+00
   1.0000e+00  -4.9916e-01  -2.2368e-01
   1.0000e+00  -4.8673e-02   1.0904e+00
   1.0000e+00   2.3774e+00  -2.2368e-01
   1.0000e+00  -1.1334e+00  -2.2368e-01
   1.0000e+00  -6.8287e-01  -2.2368e-01
   1.0000e+00   6.6103e-01  -2.2368e-01
   1.0000e+00   2.5081e-01  -2.2368e-01
   1.0000e+00   8.0070e-01  -2.2368e-01
   1.0000e+00  -2.0345e-01  -1.5378e+00
   1.0000e+00  -1.2592e+00  -2.8519e+00
   1.0000e+00   4.9477e-02   1.0904e+00
   1.0000e+00   1.4299e+00  -2.2368e-01
   1.0000e+00  -2.3868e-01   1.0904e+00
   1.0000e+00  -7.0930e-01  -2.2368e-01
   1.0000e+00  -9.5845e-01  -2.2368e-01
   1.0000e+00   1.6524e-01   1.0904e+00
   1.0000e+00   2.7864e+00   1.0904e+00
   1.0000e+00   2.0299e-01   1.0904e+00
   1.0000e+00  -4.2366e-01  -1.5378e+00
   1.0000e+00   2.9863e-01  -2.2368e-01
   1.0000e+00   7.1262e-01   1.0904e+00
   1.0000e+00  -1.0075e+00  -2.2368e-01
   1.0000e+00  -1.4454e+00  -1.5378e+00
   1.0000e+00  -1.8709e-01   1.0904e+00
   1.0000e+00  -1.0037e+00  -2.2368e-01

总和:

ans =

       4.7000e+01   1.0885e-15   1.2684e-14

第1列的总和是正确的,但其他的却是正确的。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

第2列和第3列看起来像是大约为零。每个元素都是浮点值,有时在添加和减去浮点数时会丢失一些精度。而不是看到零,你只是看到一个非常小的数字(10 ^ -15!)。一个简单的解决方法是将所有低于某个阈值的数字设置为零:

mysum = sum(X);
mysum(mysum < 1e-12) = 0

ans = 

47.0000   0   0