ONLY DO WHAT ONLY YOU CAN DO

こけたら立ちなはれ 立ったら歩きなはれ

C#で非線形方程式を解く (正割法)

非線形方程式の解法(正割法 または 割線法, セカント法 ともいう)を利用して2の平方根を求める

f:id:fornext1119:20140611080249p:plain
考え方はニュートン法と同じだが, 接線の傾きを導関数から求めるのではなく,
 \displaystyle\frac{f(x_1)-f(x_0)}{x_1-x_0} で求める.
漸化式は ニュートン法 x_1 = x_0 - \displaystyle\frac{f(x_0)}{f'(x_0)} に対して,
 x_2 = x_1 - \displaystyle\frac{f(x_1)(x_1 - x_0)}{f(x_1) - f(x_0)} となる.

using System;

public class CS0906
{
    public static void Main()
    {
        double x0 = 1;
        double x1 = 2;

        while (true)
        {
            double x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
            Console.WriteLine(string.Format("{0,12:F10}", x2));

            if (Math.Abs(x2 - x1) < 0.0000000001) break;
            x0 = x1;
            x1 = x2;
        }
    }
    
    private static double f(double x)
    {
        return x * x - 2;  
    }
}
1.3333333333
1.4000000000
1.4146341463
1.4142114385
1.4142135621
1.4142135624
1.4142135624
参考文献