Natural logarithm method for NSNumber and NSDecimalNumber

I have C # code that I am converting to Objective-C. In C #, I would call Math.Log (). I am slowly learning that some people stick with C functions / types and use NSNumber etc. when they need to interact with Cocoa.

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

This code needs to be run on iPhone if it matters.

+2


source to share


3 answers


NSNumber

useful for storing in NSArray

or NSDictionary

or master data storage.

You don't want to use NSNumber

for arithmetic, only for use with base or base data classes when you need to store that number somewhere.

This is due to the fact that when the arithmetic operations you have to constantly convert between NSNumber

and primitive types, such as int

, double

, long

, etc. Perform operations on primitive types with the required precision, and then instantiate NSNumber

if you really need it.

However, it is quite easy to use the C-math library in any Cocoa / Cocoa Touch application:



#import <math.h>

...

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

      

This is the same story for the NSDecimalNumber

subclass NSNumber

:

You can 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, such as an NSArray or NSDictionary instance. You can also consider the C interface if you want maximum efficiency. The C interface is faster and uses less memory than the NSDecimalNumber class.

+5


source


Or you are using a C function log()

that sacrifices some precision when converting decimal numbers to binary numbers. Or are you looking for a decimal library. Cocoadev has several suggestions , notably the utility bc

and the GNU General Purpose Arithmetic Library Library .



+2


source


The family of functions log()

is your best choice. A man page is available here .

0


source







All Articles