vappolinario - 1 year ago 141

C# Question

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**