views:

53

answers:

3

Let's say I'm writing a "DayData" class, containing the ivars

NSString *symbol;  //such as "AAPL"
NSString *currency; //such as "USD"
NSDate *day;
double open;
double high;
double low;
double close;

The last four ivars are the open,high,low,close prices of that stock for that day.

Say I'm using this class as the fundamental building-block class behind intensive Monte Carlo simulations along many decades, i.e. thousands of days, of historical data. This means I'd have to access these ivars thousands if not millions if not billions of times in a short period of time to make the simulations as fast as possible.

Question: Should I stick to double, or should I still use NSDecimalNumber? How fast is NSDecimalNumber, really? Has anyone here tested NSDecimalNumber for intensive scientific applications?

+2  A: 

Faster than NSDecimalNumber would be NSDecimal, which isn't an Obj-C object, so doesn't incur the overhead of objc_msgSend, but still has the advantages of decimal math. Here are the functions to work with NSDecimals.

jtbandes
Hmm. Do you maybe have some code examples on how you would use NSDecimal? Because it seems that the variables in NSDecimal are private. Is the only way to create an NSDecimal through the NSDecimalNumber class? This is kind of confusing.
Enchilada
@enchilada: Yeah, unfortunately, it look like you have to create it like `NSDecimal d = [[NSNumber numberWithInt:(some number)] decimalValue]`. But then you can use the faster C functions on it.
jtbandes
+1  A: 

If you are dealing with dollars and cents (but always whole cents), nothing is faster or more efficient than a regular int counting the cents, and dividing by 100 to get dollars.

Potatoswatter
+1  A: 

As jtbandes has said, you should use NSDecimal if you want speed, NSDecimalNumber is an Obj-C object wrapper around NSDecimal. NSDecimal is a struct used to represent decimal numbers, which allows you to do calculations that don't give binary->decimal rounding and representation errors.

I would go with double, since it's a simulation, where the last ounce of accuracy probably won't matter anyway (presumably your simulation includes approximation, so minuscule errors won't have too much of an effect). You need to beware of the pitfalls of floating point calculations - certain types of operations can lead to larger errors, especially if the magnitude of two floating point numbers are very different, or if you subtract one number from another that is very close. This page on Wikipedia covers a few of the pitfalls.

Nick Forge