2

I am trying to convert a Matlab code to Python, as below. Both codes behave the same up to the line where variable a is calculated. But when a sum operation is done, both of the codes produces different result as can be seen by b's output.

Keen to learn how to get the same results in Python as it was in 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
Saravanan K
  • 672
  • 3
  • 10
  • 27
  • 4
    Both are near zero and differ by epsilon. That is due to floating point precision or different implementations of `exp`. – rahnema1 Feb 05 '18 at 08:17
  • In addition to the comment made by @rahnema1, it also depends on different languages ultimately due to the way the code eventually gets translated into machine code. This website can provide more insight: https://0.30000000000000004.com – rayryeng Feb 05 '18 at 08:39

0 Answers0