Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top