Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising a decimal to a power of decimal?

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?

like image 839
vappolinario Avatar asked Jan 09 '09 18:01

vappolinario


People also ask

What does it mean to exponent a decimal?

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} .

What is 10 to the power of decimal?

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.


2 Answers

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).

like image 118
vappolinario Avatar answered Sep 22 '22 08:09

vappolinario


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; } 
like image 20
user1668969 Avatar answered Sep 21 '22 08:09

user1668969