Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

sverrisson

macrumors newbie
Original poster
Jan 14, 2011
13
0
Reykjavik
What to use double, long double, CGFLoat or NSNumber?

I am writing a program that does math on the iPhone. I need to have at least 15 digit precision in the math which is basic and not heavy iteration (thus speed is not big factor).
I am confused in what to do math in Objective-C. Should I use primitives as Double and Long double or use object wrappers like NSNumber (which I use in the end to get correct localization formatting).

I have not been able to get much info on this and must books on iOS development seem to skip these subjects.

Please recommend what to use. For example if I use Long Double I get 18 digit precision, but can I use the math.h libraries? Are the math.h libraries the only way to do math on iPhone or should I use OpenGL math?
 
Most likely you should use the primitive types, if there's one that gives you the precision you need. I'm not 100% certain that long double is really different than double. You should check that. Obviously math.h provides a lot of the standard math functions that work with floating point types.

NSNumber serves mostly to store values in containers and some other places where some generality is required in APIs. It's not meant for doing math, except in a simple manner.

You might also look at some of the other number classes like NSDecimalNumber. I'm not really familiar with them.

There also might be classes or code that you can find on the net for math with arbitrary precision numbers.
 
pow(x,y)

I have come at standstill using NSDecimalNumber because there are no functions for calculating powers, exponents or logarithms of functions except where the power is an integer.
Does some one now of APIS or open source algortihms for functions that I can use for this. If I get a function for calculating ln and exp then I can use that for calculating all powers.
Can anyone help?
 
An IEEE double will give you at least 52 binary bits or 15 decimal digits of precision. If you want more precision than offered by an float double math, then you will probably have to port and include your own or a 3rd party math library.

One question is do you really need the results of the log(), exp(), or non-integer power functions to have more than 15 decimal digits of precision?
 
Thanks for your responce. I wanted 20 digits of precision and NSDecimalNumber provides 38 digit precision, but it was just missing the pow() function for non-integer (real) powers.
I have spent the whole day searching on the net and have found a gnu project doing this for C: http://gmplib.org/
The GNU Multiple Precision Arithmetic Library.

But it is lacking in explanation on the algorithms used. Does anyone know about reading material on large number math?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.