3

I need an equivalent to C's pow() function that will work with NSDecimalNumbers. With pow you can use negative numbers e.g. pow(1514,-1234), with NSDecimal's decimalNumberByRaisingToPower: method, you are forced to use an NSUInteger which seems to require a positive value.

I'd like to be able to do something like this:

[decimalNumber decimalNumberByRaisingToPower:-217.089218];

or

[decimalNumber decimalNumberByMultiplyingByPowerOf10:-217];

without crashing from overflow or underflow exceptions.

james_womack
  • 10,028
  • 6
  • 55
  • 74

3 Answers3

4

Mathematically, a^(-b) == 1/(a^b). Therefore, if you just need to raise to a negative integral power,

decimalNumber = [decimalNumber decimalNumberByRaisingToPower:1234];
decimalNumber = [[NSDecimalNumber one] decimalNumberByDividingBy:decimalNumber];

For non-integral powers, there's no way except (1) implement the pow() algorithm yourself or by 3rd party libraries, or (2) performing the calculation in floating point (thus losing precisions).

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

Incidentally, you appear to be correct about decimalNumberByRaisingToPower, but, from the Apple docs:

(NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power

That's not unsigned.

Stephan
  • 41,764
  • 65
  • 238
  • 329
Fred Fnord
  • 11
  • 1
0

You can first convert decimalNumber to its doubleValue and then just call the pow function of C++. I haven't tried it but I think it should work. Refer: Calling Objective-C method from C++ method? for mixing c++ and objective c.

Community
  • 1
  • 1
cooltechnomax
  • 681
  • 3
  • 10
  • 21