iOS——实现复数
作为这个问题的后续行动:
我正在实现一个计算器应用程序使用 Apple 的复数支持 当我注意到如果使用该支持进行计算时,最终会得到以下结果:
(1+i)^2=1.2246063538223773e-16 + 2i
当然,正确的恒等式是 ( 1+i)^2=2i。这是一个更普遍现象的具体示例——如果舍入误差将本应为零的部分舍入为稍微非零的部分,那么舍入误差可能会非常烦人。
关于如何处理这个问题的建议?我可以用其他方式实现复数的整数幂,但一般问题仍然存在,而且我的解决方案本身可能会导致其他不一致。
As a follow-up to this question:
I was in the process of implementing a calculator app using Apple's complex number support when I noticed that if one calculates using that support, one ends up with the following:
(1+i)^2=1.2246063538223773e-16 + 2i
Of course the correct identity is (1+i)^2=2i. This is a specific example of a more general phenomenon -- roundoff errors can be really annoying if they round a part that is supposed to be zero to something that is slightly nonzero.
Suggestions on how to deal with this? I could implement integer powers of complex numbers in other ways, but the general problem will remain, and my solution could itself cause other inconsistencies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所注意到的,这是浮点的标准舍入误差问题。 @Howard 指出,您可能应该在显示之前将双精度结果舍入到浮点范围内。
我通常也使用
FLT_EPSILON
来帮助我处理此类事情。有了这些,您可能会喜欢这样的函数(未经测试),
正如他们所说,复杂的版本留给读者作为练习:D
As you note, this is as standard rounding error issue with floating points. A @Howard notes, you should likely round your double results back into the float range before displaying.
I typically use
FLT_EPSILON
to help me with these kinds of things as well.With those, you might like a function like this (untested)
The complex version is left as an exercise for the reader as they say :D