3

Ok so Im trying to raise this fractional amount to a high power. But for some reason, according to the logs I just get a very high number and sometimes even a NSDecimalOverflor error. Could someone please help me with this?

NSDecimalNumber *number = [[NSDecimalNumber alloc] initWithDouble:0.4];
NSInteger power = 1001;

number = [number decimalNumberByRaisingToPower:power];

NSLog(@"%@",number);

Maybe I'm hitting some sort of limit with the number being too small? Anything would help!

edit: oh and stack trace shows all the numbers are the same when it breaks in actual context.

Michael Giba
  • 118
  • 4

1 Answers1

1

From Apple docs:

NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

So there is a limit, consider floating point double.

0.4 ^ 1001:
4e-399
or
0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001

Which are much larger than NSDecimalNumber can handle.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • Very nice thank you for the response. Do you know why this overflow would sometimes cause a large number to appear? – Michael Giba Nov 06 '13 at 01:27
  • The results of overflow are "undefined". Bad things happen, and the answers are invalid. Typically the different parts of the number (mantissa, exponent, sign bits, etc) bleed over into each other. – Duncan C Nov 06 '13 at 02:24
  • According to Apple: "The methods assume your need for precision does not exceed 38 significant digits and raise exceptions when they try to divide by 0 or produce a number too big or too small to be represented." – zaph Nov 06 '13 at 03:06
  • I tried to get fancy and stray away from double to attempt to preserve some accuracy during some calculations.... Never again! – Michael Giba Nov 06 '13 at 05:32