views:

192

answers:

3

I've got some C# code that I'm converting to Objective-C. In C# I would call Math.Log(). I'm slowly learning that some people stick to C functions/types and only use NSNumber etc when they need to interop with Cocoa.

Is there an equivalent for ObjC/Cocoa, or do I need to drop into C to do this? I need my code to be as accurate as possible because it is part of a calculator.

This code needs to run on iPhones if that makes any difference.

A: 

The family of log() functions is your best bet. Man page available here.

Carl Norum
+3  A: 

NSNumber is useful for storage in NSArray or NSDictionary, or in a Core Data store.

You don't want to use NSNumber for arithmetic, only for use with foundation or Core Data classes when you need to store that number somewhere.

This is because you will have to constantly convert between NSNumber and primitive types like int, double, long, etc. when performing arithmetical operations. Do the operations with the primitive types to the desired accuracy, and then create an NSNumber instance, if you really need one.

Nonetheless, it is fairly trivial to use the C math library in any Cocoa/Cocoa Touch app:

#import <math.h>

...

double _param = 7.389;
NSNumber *_result = [NSNumber numberWithDouble:log(_param)];

This is the same story for NSDecimalNumber, which is a subclass of NSNumber:

You might consider the C interface if you don’t need to treat decimal numbers as objects—that is, if you don’t need to store them in an object-oriented collection like an instance of NSArray or NSDictionary. You might also consider the C interface if you need maximum efficiency. The C interface is faster and uses less memory than the NSDecimalNumber class.

Alex Reynolds
`NSDecimalNumber` implements some rudimentary math functions. Sadly not logarithms.
Georg
Note that the C interface referred to in the quoted text is for the NSDecimal struct, not your standard floating point or integer types.
Brad Larson
"This is the same story for `NSDecimalNumber`..."
Alex Reynolds
+1  A: 

Either you use C's log() function which sacrifices some precision as you convert decimal numbers to binary ones. Or you look for a decimal numbers library. Cocoadev has some suggestions, especially the bc utility and the GNU Multiple Precision Arithmetic Library library.

Georg