Two quick questions if I may, is this how I should go about taking two NSNumber objects, performing a calculation and ending up with a result that is also an NSNumber?
NSNumber *flux = [[NSNumber alloc] initWithDouble:100.0];
NSNumber *mass = [[NSNumber alloc] initWithDouble:3];
double intermediate = [flux doubleValue] / [mass doubleValue];
NSLog(@"INTER : %.20f", intermediate);
NSNumber *result = [[NSNumber alloc] initWithDouble:intermediate];
NSLog(@"RESULT: %@", result);
...
...
[flux release];
[mass release];
[result release];
Also looking at the results in console from NSLog, is there any loss of precision? I would assume there is not and what I am seeing is just display precision, but just curious?
INTER : 33.33333333333333570181
RESULT: 33.33333333333334
gary
(Tangential to your question but related)
NSNumber isn’t intended to do base-10 math with. It’s largely there to wrap and store numerical values. If you need to do real math, you want to use a NSDecimal.
Despite the fact that we call them “computers” our logic engines can’t do actual math so they have to fake it. When you get to the extremes of very large or very small magnitude numbers, that faking begins to show. That is why you need custom numerical classes that can hold more information than just a string of digits.
So, if you have any concerns about precision, use NSDecimal instead of NSNumber. NSDecimal is designed to perform precise calculations.
Edit01:
Strictly speaking, you should not use NSNumber for calculations. You will notice that NSNumber has no dedicated methods for doing math. You have to convert to scalar and then back again to an object. This causes a loss of precision and the precision can change depending on the hardware or the definitions of the scalars.
NSDecimal by contrast can precisely represent very precise numbers because it holds them abstractly. It has dedicated methods for performing precise mathematical operations.
Yes, there is a loss of mathematical precision beyond just the formatting. Scalars have different precision depending on their type and size of the number they store.. At large magnitudes, this causes problems with precision. If you mix types, say a NSInteger and a NSUInteger, you get the maximal precision of the NSInteger.
You also run into all the old problems of using scalars.
NSDecimal frees you from all these possible sources of error. It does precise mathematical calculations up to magnitudes way beyond what anyone would use in the real world.
I repeat: If precision is a concern, don’t use NSNumber or scalar.