The .net framework provides in the Math class a method for powering double. But by precision requirement I need to raise a decimal to a decimal power [ Pow(decimal a, decimal b) ]. Does the framework have such a function? Does anyone know of a library with this kind of function?
The exponent tells you how many times the base is being used as a factor in the expression. For example, 3 4 = 3 × 3 × 3 × 3 = 81 {\displaystyle 3^{4}=3\times 3\times 3\times 3=81} .
Thus, shown in long form, a power of 10 is the number 1 followed by n zeros, where n is the exponent and is greater than 0; for example, 106 is written 1,000,000. When n is less than 0, the power of 10 is the number 1 n places after the decimal point; for example, 10−2 is written 0.01.
To solve my problem I found some expansion series, and them I had them implemented to solve the equation X^n = e^(n * ln x).
// Adjust this to modify the precision public const int ITERATIONS = 27; // power series public static decimal DecimalExp(decimal power) { int iteration = ITERATIONS; decimal result = 1; while (iteration > 0) { fatorial = Factorial(iteration); result += Pow(power, iteration) / fatorial; iteration--; } return result; } // natural logarithm series public static decimal LogN(decimal number) { decimal aux = (number - 1); decimal result = 0; int iteration = ITERATIONS; while (iteration > 0) { result += Pow(aux, iteration) / iteration; iteration--; } return result; } // example void main(string[] args) { decimal baseValue = 1.75M; decimal expValue = 1/252M; decimal result = DecimalExp(expValue * LogN(baseValue)); }
The Pow() and Factorial() functions are simple because the power is always an int (inside de power series).
This should be the fastest for a positive integer Exponent and a decimal base:
// From http://www.daimi.au.dk/~ivan/FastExpproject.pdf // Left to Right Binary Exponentiation public static decimal Pow(decimal x, uint y){ decimal A = 1m; BitArray e = new BitArray(BitConverter.GetBytes(y)); int t = e.Count; for (int i = t-1; i >= 0; --i) { A *= A; if (e[i] == true) { A *= x; } } return A; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With