gpt4 book ai didi

python - numpy.fft.fft 与高精度数字的意外行为

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:43 31 4
gpt4 key购买 nike

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

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 的预期结果... enter image description here

但是,如果您以等于 2.*numpy.pi 的更高精度 6.283185307179586 运行代码,您会得到下面意想不到的结果...实部完全错误...幅度相差很大,它不对称,没有任何意义。 enter image description here

我不知道是什么原因造成的。大家有什么想法吗?

最佳答案

这完全是预期的行为。计算机使用浮点计算,本质上是不精确的。

注意实际结果的 y 轴。如果不存在数值误差,则实部将完全相同 0。使用“更高精度”结果,实部几乎与 0 相同(1e-14 非常接近 double float 的精度)。精度较低时,实部会变得更大(尽管仍然比虚部小得多)。由于数字较大,结构也更多(即误差不是由舍入误差给出的,而是由输入数据的实际特征给出的,即比理想周期稍短的周期)。

关于python - numpy.fft.fft 与高精度数字的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57383041/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com