Pixel Pedals of Tomakomai

北海道苫小牧市出身の初老の日常

問題3.21の解答(ニュートン法)

概説微分積分の問題3.21の解答。

x^3 + x^2 - 3 = 0 と x^4 - x - 1 = 0 を解く問題。

def f1(x):
    return float(x) ** 3 + float(x) ** 2 - 3

def df1(x):
    return 3. * float(x) ** 2 + 2. * x

def f2(x):
    return float(x) ** 4 - float(x) - 1

def df2(x):
    return 4. * float(x) ** 3 - 1

def newton(f, df, a0, n):
    if n == 0: return a0
    a = newton(f, df, a0, n-1)
    return a - float(f(a)) / df(a)

x1 = newton(f1, df1, 2, 3)
print "x = %.4f, f(x) = %.4f" % (x1, f1(x1))

x2 = newton(f2, df2, 2, 3)
print "x = %.4f, f(x) = %.4f" % (x2, f2(x2))
x = 1.1756, f(x) = 0.0065
x = 1.2358, f(x) = 0.0964

下に凸な関数について、接線使って上から解に寄せていってるだけ。