开发者

Problem with adding two double values in objective c

I'm programming an app for iphone and ipad and my program requires adding two double valu开发者_StackOverflowes to get a single double value. The problems is when one of the double values is fairly large (eg: 2^100) and the other one is very small like 1 or 2, the result of adding those two double values is wrong or it doesn't even do the addition. Does anyone know why that is and if there's a way around it. Thank you.


This has nothing to do with obj-c. A double is a 64-bit datatype that stores a floating-point value. In decimal, a double can hold approximately 15.955 digits of precision. However, your 2^100 number has about 30 decimal digits. So if you try and add anything up to about 1 quadrillion to it, you'll find that the addition doesn't work since that falls outside of the precision range of your number.

In order to get around this, you can use NSDecimalNumber, which will hold up to 38 decimal digits of precision.


This is a good read for anyone dealing with floating-point numbers:

http://en.wikipedia.org/wiki/Floating_point

The situation you describe is completely normal, and is a natural outcome of how floating point works on computers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜