Python与Matlab代码中数组求和的差异
这里有一个链接,里面有一个叫做temp的mat文件,我想要计算它的总和。在Python中计算的结果是1.1230325644146074e-10,而在Matlab中计算的结果是1.2189e-010。但是,当我把Matlab中的数组复制到Python终端并进行相加时,我得到的总和和Matlab的一样。这其中有什么奥秘呢?
>>> np.sum(temp)
1.1230325644146074e-10
>>> 0 + 1.34369215036371e-13 + 1.44714547828739e-11 + 3.13077747300113e-11 + 0 +
7.33156408714693e-10 + 1.07579271945635e-08 + 8.89446393156299e-09 + 0 +
8.00303861023109e-08 + 9.10095259764947e-07 + 6.44662571715407e-07 + 0 +
6.16697002187199e-06 + 0.000104686113649727 + 0.000240373037717048 +
7.07802623602744e-11 + -0.000240372993389479 + -0.000104686106424492 +
-6.16697038783319e-06 + 0 + -6.44662640770614e-07 + -9.10095265552302e-07 +
-8.00303919930304e-08 + 0 + -8.89446408625544e-09 + -1.07579272042352e-08 +
-7.33156409297323e-10 + 0 + -3.13077747365376e-11 + -1.44714547888711e-11 +
-1.34369215245131e-13
1.218862069269912e-10
我之所以需要这些,是因为下面代码中的num是从temp得来的,然后我有一个分母部分,我正在尝试进行除法运算。所以即使这些值很小,但如果存在小的误差,它们的除法在我把Matlab代码转到Python时就会产生错误。
这是Matlab代码。
function mth = compute_mean_angle(dEnergy,th)
global NFFT;
sth = sin(2*th);
cth = cos(2*th);
num = sum(sum(dEnergy.*sth));
den = sum(sum(dEnergy.*cth));
mth = 0.5*atan2(num,den);
if(mth <0)
mth = mth+pi;
end;
%end function compute_mean_angle
这是Python代码。
def compute_mean_angle(dEnergy, th):
global NFFT
sth = np.sin(np.dot(2, th))
cth = np.cos(np.dot(2, th))
num = np.sum(np.sum(dEnergy * sth))
den = np.sum(np.sum(dEnergy * cth))
mth = np.dot(0.5, math.atan2(num, den))
if (mth < 0):
mth = mth + np.pi
return mth
我在这里附上了样本文件,点击这里。里面包含了三个文件:temp.mat、dEnergy.mat和th.mat。
1 个回答
1
无法重现:
MATLAB
>> load('temp.mat')
>> whos temp
Name Size Bytes Class Attributes
temp 1x32 256 double
>> sum(temp)
ans =
1.2189e-10
>> sprintf('%.16e', ans)
ans =
1.2188620688216985e-10
Python
>>> import numpy as np
>>> import scipy.io
>>> t = scipy.io.loadmat("temp.mat")
>>> who(t)
Name Shape Bytes Type
===========================================================
temp 1 x 32 256 float64
Upper bound on total bytes = 256
>>> np.sum(t["temp"])
1.2188620688216985e-10
编辑
针对评论,再次说明结果基本相同:
MATLAB
>> load('dEnergy.mat')
>> load('th.mat')
>> mth = compute_mean_angle(dEnergy,th);
>> sprintf('%.16e', mth)
ans =
1.5707963267948966e+00
Python
>>> m1 = scipy.io.loadmat("dEnergy.mat")
>>> m2 = scipy.io.loadmat("th.mat")
>>> compute_mean_angle(m1["dEnergy"], m2["th"])
1.5707963267948966