高精度数字numpy.fft.fft的异常行为 [英] Unexpected behavior of numpy.fft.fft with high precision numbers

查看:217
本文介绍了高精度数字numpy.fft.fft的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码...请注意#生成生成正弦曲线的两行.一个使用2pi的精度值要比另一个使用更高的精度,尽管如此,它们仍应给出几乎相同的结果.

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()

如果以较低的精度6.28318运行代码,则会得到fft的预期结果...

If you run the code with the lower precision 6.28318 you get the expected result for the fft...

但是,如果您以更高的精度6.283185307179586(等于2. * numpy.pi)运行代码,则会在下面得到意外的结果...实际部分完全错误...幅度相差甚远,它不是对称的,没有任何意义.

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.

我不知道是什么原因造成的.有人有什么想法吗?

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

推荐答案

这完全是预期的行为.计算机使用浮点计算,这本来就不精确.

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

请注意实际结果的y轴.如果不存在数值误差,则实数部分将等于0.使用​​更高的精度"结果,实数部分几乎等于0(1e-14非常接近于双精度浮点数的精度).精度较低时,实部会变得更大(尽管仍然远大于虚部).由于数量较大,因此结构也更多(即,错误不是由舍入误差引起的,而是由输入数据的实际特征决定的,周期略短于理想值).

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).

这篇关于高精度数字numpy.fft.fft的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆