Home > OS >  Why is the result of numpy fft different from matlab fft?
Why is the result of numpy fft different from matlab fft?

Time:12-02

I was using parameters and formulations below to generate signals.

python code:

import numpy as np

fs=15e6
dt=1/fs
f0=1e6
pri=400e-6
t=np.arange(0,dt,pri)
i=64
fd=5/(i*pri)
xt=0.1*np.exp(2j*np.pi*f0*t)
xf=np.fft.fft(xt)

matlab code is very similar with python code:

fs=15e6
dt=1/fs
f0=1e6
pri=400e-6
t=0:dt:pri-dt
i=64
fd=5/(i*pri)
xt=0.1*exp(2j*pi*f0*t)
xf=fft(xt)

These code will generate an array of length 6000 to perform fft. Then I calculate the result in matlab using the same method. The result is absolutely same when the fft length is less than 6000. But it became a little different when the fft length is 6000. I was confused. Can anybody illustrate this phenomenon? Thanks for your help. PS: python 3.8.5, numpy 1.19.2, matlab 2014

CodePudding user response:

Your difference is because Python’s

t=np.arange(0,dt,pri)

is not the same as MATLAB’s

t=0:dt:pri-dt

In MATLAB you are generating values from 0 to pri (not included), in steps of dt. In Python you are generating numbers from 0 to dt (not included), in steps of pri.

Please read the documentation to np.arange.

CodePudding user response:

demio. I think the different values you are getting is because MATLAB's floating point rounding errors. For low values, of order 1e-15, that values are rounded to 0 and that generates an error of the order that is being rounded to. It happens the same way for really big values. You can see a related post with pretty good explanation of this on: https://es.mathworks.com/matlabcentral/answers/475494-unexpected-results-due-to-floating-point-rounding-errors-by-performing-arithmetic-calculations-on-la.

Also it is worth noticing that even though this floating point rounding errors always occur you have to determine whether that's significant or not taking into account your set of data and the result you are expecting. Sometimes those absolute differences does not mean anything because the relative differences are marginal. If you wish to avoid this behavior from MATLAB you need to use the sym function, that triggers MATLAB to use a Symbolic representation which involves several things, one of them being that the numbers are represented more accurately. More on this subject can be found here: https://es.mathworks.com/help/symbolic/create-symbolic-numbers-variables-and-expressions.html#buyfu27.

  • Related