Decimalの数値計算

System.Mathには無かったので自前でちまちま。

using System;

def abs (x) {
    if (x < 0.0m)
        -x
    else
        x
}

def log (x) {
    if (x <= 0.0m) {
        0.0m;
    }
    else {
        def N=9;
        mutable a = x - 1;
        mutable s = 0.0m;
        for (mutable i = N; i >= 1; --i)
            s = i * a / (2 + i * a/ (2 * i + 1 + s));
        a / (1 + s);
    }
}

def exp (x) {
    def eps = 0.00000000000000000001m; // 1.0E-20までの誤差を見る
    mutable flag = true;
    mutable a = abs (x);
    mutable s  = 1.0m;
    mutable e  = 1.0m;
    mutable d  = 1.0m;
    mutable i  = 1.0m;

    while (flag) {
        d = s;
        e = e * a / i;
        s = s + e;
        when (abs (s -d) < eps * abs (d)) {
            when (x < 0.0m)
                s = 1.0m / s;
            flag = false;
        }
        ++i;
    }
    s;
}

def n = 100000000.0m;
Console.WriteLine (exp ((n-2.0m) * log(1.0m - 1.0m / n)));

/* 結果
0.367879446689634005080244756
 */

数学に全然自信がないので、数値計算はおっかなびっくりです。(^^;