.net框架在Math类中提供了一个为double提供动力的方法.但是根据精度要求,我需要将小数提高到十进制幂[Pow(十进制a,十进制b)].框架是否具有这样的功能?有没有人知道有这种功能的图书馆?
为了解决我的问题,我找到了一些扩展序列,并且我实现了它们来解决方程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)); }
Pow()和Factorial()函数很简单,因为幂总是一个int(内部de power系列).
对于正整数Exponent和十进制基数,这应该是最快的:
// 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; }