简体   繁体   English

iOS - 实现复杂的数字

[英]iOS — implementing complex numbers

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: 我正在使用Apple的复数支持实现计算器应用程序,当我注意到如果计算使用该支持时,最终会得到以下结果:

(1+i)^2=1.2246063538223773e-16 + 2i (1 + i)^ 2 = 1.2246063538223773e-16 + 2i

Of course the correct identity is (1+i)^2=2i. 当然,正确的身份是(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. 我可以用其他方式实现复数的整数幂,但是一般问题仍然存在,而我的解决方案本身可能导致其他不一致。

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. @Howard指出,在显示之前,您应该将双倍结果回到浮动范围内。

I typically use FLT_EPSILON to help me with these kinds of things as well. 我通常使用FLT_EPSILON来帮助我处理这些事情。

#define fequal(a,b) (fabs((a) - (b)) < FLT_EPSILON)
#define fequalzero(a) (fabs(a) < FLT_EPSILON)

With those, you might like a function like this (untested) 有了这些,你可能会喜欢这样的功能(未经测试)

inline void froundzero(a) { if (fequalzero(a)) a = 0; }

The complex version is left as an exercise for the reader as they say :D 复杂的版本留给读者,因为他们说:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM