开发者

Natural logarithm method for NSNumber and NSDecimalNumber

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.

Thi开发者_如何学运维s code needs to run on iPhones if that makes any difference.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜