Is there a Math API for Pow(decimal, decimal)

Maxime ARNSTAMM picture Maxime ARNSTAMM · Jun 21, 2011 · Viewed 35.6k times · Source

Is there a library for decimal calculation, especially the Pow(decimal, decimal) method? I can't find any.

It can be free or commercial, either way, as long as there is one.

Note: I can't do it myself, can't use for loops, can't use Math.Pow, Math.Exp or Math.Log, because they all take doubles, and I can't use doubles. I can't use a serie because it would be as precise as doubles.

Answer

Eric Lippert picture Eric Lippert · Jun 21, 2011

One of the multipliyers is a rate : 1/rate^(days/365).

The reason there is no decimal power function is because it would be pointless to use decimal for that calculation. Use double.

Remember, the point of decimal is to ensure that you get exact arithmetic on values that can be exactly represented as short decimal numbers. For reasonable values of rate and days, the values of any of the other subexpressions are clearly not going to be exactly represented as short decimal values. You're going to be dealing with inexact values, so use a type designed for fast calculations of slightly inexact values, like double.

The results when computed in doubles are going to be off by a few billionths of a penny one way or the other. Who cares? You'll round out the error later. Do the rate calculation in doubles. Once you have a result that needs to be turned back into a currency again, multiply the result by ten thousand, round it off to the nearest integer, convert that to a decimal, and then divide it out by ten thousand again, and you'll have a result accurate to four decimal places, which ought to be plenty for a financial calculation.