Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

python - Unexpected behavior of numpy.fft.fft with high precision numbers

I have the following code...Note the two lines under # generate sine curve. One uses a higher precision value for 2pi than the other, they should still give near identical results though.

import numpy as np
import matplotlib.pyplot as plt


t1 = np.arange(0., 1., .01)

# generate sine curve
y1 = np.sin(6.28318*5.*t1)  
#y1 = np.sin(6.283185307179586*5.*t1) # equivalent to np.sin(2*np.pi*t1)

# calculate the fft (no averaging!) of the time series
ffty = np.fft.fft(y1)

fig, ax_list = plt.subplots(3,1)
ax_list[0].plot(t1,y1, '.-')

ax_list[1].plot(ffty.real, '.-', label='Real Part')
ax_list[1].legend()

ax_list[2].plot(ffty.imag, '.-', label='Imag Part')
ax_list[2].legend()


plt.show()

If you run the code with the lower precision 6.28318 you get the expected result for the fft... enter image description here

However, if you run the code with the higher precision 6.283185307179586 which is equal to 2.*numpy.pi, you get the unexpected result below... the real part is drastically wrong...The amplitudes are way off, it's not symmetric, it doesn't make any sense. enter image description here

I'm at a loss as to what is causing this. Anyone have any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is totally expected behavior. Computers use floating-point computations, which are inherently imprecise.

Note the y-axis for your real result. If no numerical inaccuracy existed, the real component would be identically 0. With your "higher precision" result, the real part is almost identical to 0 (1e-14 is very close to the precision of double-precision floats). With a lower precision, the real part becomes much larger (though still much, much smaller than the imaginary part). Because of the larger numbers, there is more structure as well (i.e. the error is not given by rounding errors, but by an actual feature of your input data, a period that is slightly shorter than ideal).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...