找到函数的域,给定它的根

时间:2014-11-29 19:24:28

标签: python math newtons-method

我需要帮助编写一个接收函数的方法,一些数字y并返回x,使f(x) = y。使用牛顿方法可以区分函数:

from random import *

def diff_param(f,h=0.001):
    return (lambda x: (f(x+h)-f(x))/h)


def NR(func, deriv, epsilon=10**(-8), n=100, x0=None):
""" returns a number such that f(number) == 0"""
    if x0 is None:
        x0 = uniform(-100.,100.)
    x=x0; y=func(x)
    for i in range(n):
        if abs(y)<epsilon:
            #print (x,y,"convergence in",i, "iterations")
            return x
        elif abs(deriv(x))<epsilon:
            #print ("zero derivative, x0=",x0," i=",i, " xi=", x)
            return None
        else:
            #print(x,y)
            x = x- func(x)/deriv(x)
            y = func(x)
    #print("no convergence, x0=",x0," i=",i, " xi=", x)
    return None

我需要编写一个方法source(f,y),它返回x f(x) = y

def source(f,y):

1 个答案:

答案 0 :(得分:1)

你需要找到g(x)= f(x)-y:

的零
def source(f,y):
    def g(x):
         return f(x)-y
    x = NR(g, diff_param(g))
    return x

这会返回一个x,但可能还有其他人。要找到它们,您需要尝试其他初始值x0