Skip to main content
 首页 » 编程设计

python之找到一个函数的定义域,给定它的根

2025年05月04日11xiaohuochai

我需要帮助编写一个接收函数和一些数字 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 

我需要编写一个返回 x 的方法 source(f,y) 使得 f(x) = y。

def source(f,y): 

请您参考如下方法:

您需要找到 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。