牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

SICP Exercise 1.8. ニュートン法による立方根(三乗根)をPythonでやってみた

Exercise 1.8. Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value
\frac{x/y^2 + 2y}{3}

(練習 1.8 ニュートン法において立方根は、yがxの立方根の近似値だとしたとき、より良い近似値の評価を得るには
\frac{x/y^2 + 2y}{3} という事実に基づく。)

def square(x):
    return x * x
def cubic_root_iter(old_guess, new_guess, x):
    if cubic_good_enough(old_guess, new_guess):
        return new_guess
    else:
        return cubic_root_iter(new_guess, cubic_improve(new_guess, x), x)
def cubic_improve(guess, x):
    return (x / (3 * square(guess))) + ((2 * guess) / 3.0)
def cubic_good_enough(old_guess, new_guess):
    if abs(1.0 - (old_guess / new_guess)) < 0.0001:
        return True
def cubic_root(x):
    return cubic_root_iter(1.0, x, x)

print cubic_root(2)
print 1.25992105002 ** 3
print cubic_root(8)
結果
1.25992105002
2.0000000006
2.0000000008