Take the 2-minute tour ×

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.

share|improve this question
There is no such thing as "dropping into C" from ObjC. Every C function is an objective-C function. As Alex Reynolds wrote, it's as simple as importing <math.h> and calling the log function. –  Stephen Canon Oct 27 '09 at 19:01
add comment

3 Answers

up vote 5 down vote accepted

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.

share|improve this answer
NSDecimalNumber implements some rudimentary math functions. Sadly not logarithms. –  Georg Schölly Oct 27 '09 at 18:07
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 Oct 27 '09 at 20:22
"This is the same story for NSDecimalNumber..." –  Alex Reynolds Oct 27 '09 at 21:30
add comment

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


