go - 复数的离散积分会产生错误的结果
问题描述
我目前正在尝试为复数傅立叶变换实现对复数的离散积分。
但是,我在 go 中所做的实现会产生错误的结果。
这是我的实现:
n = input() //It is a function argument
cumulativeValue := 0 + 0i
currentTime := 0.00
const deltaTime = 0.001
const precision = 0.0001
for cmpFloat(currentTime, 1.00, precision) < 0 {
currentPoint := findPointForTime(currentTime)
cumulativeValue += complex(float64(currentPoint.X), float64(currentPoint.Y)) * cmplx.Exp(complex(0.0, -2.0*math.Pi*float64(n)*currentTime))
currentTime += deltaTime
}
cumulativeValue *= deltaTime
该算法返回傅立叶级数的元素。但是当我尝试从意式中取回该功能时,它与原始输入相去甚远。
我尝试在 Python 中实现相同的算法,没有进行转换,并且它完美地工作。
调查
我首先认为问题与findPointForTime
功能有关,但我已经确认它没有。
然后,在调试时,我发现前几个值在 Python 中是相当等价的,但在第 500 次加法(中间算法)之后就不那么等价了。
那么问题可能是 go 的复数的精度不够,或者 cmplx.Exp 不正确(这似乎不太可能)。
那么,有没有办法提高 go 中 complex128 的精度呢?
TLDR:问题可能是 go 的浮点精度。有没有办法改进它?
- 注 1:奇怪的是,该代码仅适用于一个输入,而到目前为止不适用于其他输入。
- 注意 2:我的代码(很大程度上)是从其他人那里获得灵感的,并且在他们的情况下有效,这让我认为不需要其他库,例如“math/big”(尽管它可能值得尝试)。
编辑
- 编辑1:积分不依赖于deltaTime,因为它是我积分的间隔(因此,它是一个乘法因子,并且,作为一个常数,它可以在循环内或循环外),但是它取决于 currentTime 变量。
根据复杂的傅立叶变换的工作原理,积分是
所以我首先得到值 f(t) 然后我计算指数部分,将它们与 deltaTime 相乘(我把它留在外面 - 在循环结束时)和将它们添加到累加器中。最后,我在 currentTime 低于 1 秒时重复此操作。(我相信哪个是与楼梯整合的方法=>也许梯形更好?) - 编辑 2:我使用的是 python 的默认复杂系统,所以我怀疑它是 128 位的。python代码如下:
currentTime = 0
deltaTime = 0.001
cumulativeValue = complex(0)
while currentTime < 1.0:
point = getPointforTime(currentTime)
cumulativeValue += point * cmath.exp(-2.0j*cmath.pi*n*currentTime)*deltaTime
currentTime += deltatime
解决方案
推荐阅读
- keras - Keras 的多输出多分类问题
- variables - 具有动态变量名称的 TCL/TK 单选按钮
- fortran - Fortran 90:字符串的重复元素
- django - Django 自定义身份验证 get_user() 错误
- javascript - 反应收集器,显示百分比(用于建议)
- java - 为什么抛出未经检查的异常会消除“缺少返回语句”错误
- javascript - 使用 Jquery 删除任何 CSS 文件?
- react-native - 如何从 FlatList 项目中获取 AsyncStorage 键名以删除?
- javascript - 为什么我的 JS 方法不会设置我的实例的参数?
- c++ - 如何在vscode for c ++中将花括号放在新行上?