python Newton Method求平方根

# -*- coding : utf-8 -*-

def improve(update, close, guess=1):
    if not close(guess):
        guess = update(guess)
    return guess

def approx_eq(a, b, tolerance=1e-15):
    return abs(a - b) < tolerance

def newton_update(f, df):
    def update(x):
        return x - f / df
    return update

def find_zero(f, df):
    def near_zero(x):
        return approx_eq(f(x), 0)
    return improve(newton_update(f, df), near_zero)


def square_root_newton_method(a):
    """ Find the square root of a positive number a """
    def f(x):
        return x * x - a
    def df(x):
        return 2 * x
    return find_zero(f, df)

你可能感兴趣的:(python Newton Method求平方根)