Sum运算在Matlab / Python中产生不同的结果

时间:2018-02-05 07:59:00

标签: python matlab

我正在尝试将Matlab代码转换为Python,如下所示。 两个代码在计算变量a的行之前表现相同。但是当sum操作完成时,两个代码都会产生不同的结果,如b的输出所示。

热衷于学习如何在Python中获得与Matlab相同的结果。

Matlab的

M = 512;
C = 16;
k=[-(C-1)/2:(C-1)/2].*ones(1,C);
% k = [-7.50000000000000,-6.50000000000000,-5.50000000000000,-4.50000000000000,-3.50000000000000,-2.50000000000000,-1.50000000000000,-0.500000000000000,0.500000000000000,1.50000000000000,2.50000000000000,3.50000000000000,4.50000000000000,5.50000000000000,6.50000000000000,7.50000000000000]
n=1;

a = exp(j*2*pi*k*(n)/(C));
% a = [-0.980785280403230 - 0.195090322016129i,-0.831469612302545 - 0.555570233019602i,-0.555570233019602 - 0.831469612302545i,-0.195090322016128 - 0.980785280403230i,0.195090322016128 - 0.980785280403230i,0.555570233019602 - 0.831469612302545i,0.831469612302545 - 0.555570233019602i,0.980785280403230 - 0.195090322016128i,0.980785280403230 + 0.195090322016128i,0.831469612302545 + 0.555570233019602i,0.555570233019602 + 0.831469612302545i,0.195090322016128 + 0.980785280403230i,-0.195090322016128 + 0.980785280403230i,-0.555570233019602 + 0.831469612302545i,-0.831469612302545 + 0.555570233019602i,-0.980785280403230 + 0.195090322016129i]

b = sum(a);
% b = 1.55431223447522e-15 + 6.38378239159465e-16i

的Python

import numpy

M = 512
C = 16
k = numpy.linspace(-(C-1)/2, (C-1)/2, C)
# k = [-7.5,-6.5,-5.5,-4.5,-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5]
n=1

a = numpy.exp(1j * 2 * numpy.pi * k * n / C)
# a = [-0.98078528 - 0.19509032j,-0.83146961 - 0.55557023j,-0.55557023 - 0.83146961j,-0.19509032 - 0.98078528j,0.19509032 - 0.98078528j,0.55557023 - 0.83146961j,0.83146961 - 0.55557023j,0.98078528 - 0.19509032j,0.98078528 + 0.19509032j,0.83146961 + 0.55557023j,0.55557023 + 0.83146961j,0.19509032 + 0.98078528j,-0.19509032 + 0.98078528j,-0.55557023 + 0.83146961j,-0.83146961 + 0.55557023j,-0.98078528 + 0.19509032j]

b = numpy.sum(a)
# b = 6.661338147750939e-16 - 2.7755575615628914e-17j

0 个答案:

没有答案