简体   繁体   中英

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:

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

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.

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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