需求:实现支持用户输入函数并自动求导的Python数值计算程序
需求说明
我正在开发一个Python程序,要实现让用户输入函数后自动求导,用于数值方法计算。目前已有一个计算导数真实值、近似值及误差的程序(代码如下,这是我第一个Python程序,代码有点乱),现在需要修改程序,让它支持用户自定义输入函数并自动求导,之后继续完成原有的数值计算流程,包括近似值、真实值、误差等计算。我知道这个功能在MATLAB里更容易实现,但我没法访问MATLAB。
原有代码
def ggxp(x,h): z1= int(((ggx(x)*ggx(h)) - ggx(x))/h) return z1 def ggxd(x): z2= 4*x+1 return z2 def ggx(x): z3= int(2*x^2+x-5) return z3 x = int(input("Enter x \n")); c =2; while c > 0: h= int(input("Enter h \n")) y0 = ggxd(x) y1= ggxp(x,h) TrueError=y0-y1; print("The approximate value at ", x ," is ", y1 ," \n") if c == 2: prevA = y1; c= c-1; print ("The true value at ",x," is ",y0,"\n") RelativeTE= int((TrueError/y0)*100); print ("the relative true error is ", RelativeTE ,"\n") if prevA != y1: Ea = int(prevA - y1); REa = int((Ea / y1) * 100) print("The approximate error is " , Ea , "\n") print("The relative approximate error is ", REa, "\n")
修改后的程序
import sympy as sp def numerical_derivative(f, x, h): # 向前差分近似求导(修正原代码逻辑错误) return (f(x + h) - f(x)) / h def main(): # 获取用户输入 func_str = input("请输入函数(用x做变量,比如2*x**2 + x -5):") x_val = float(input("请输入求导点x的值:")) # 解析用户输入的函数并处理符号求导 x = sp.symbols('x') try: f_sym = sp.sympify(func_str) except Exception as e: print(f"函数输入不对:{e}") return # 自动求导并转换为可计算数值的函数 f_prime_sym = sp.diff(f_sym, x) f = sp.lambdify(x, f_sym, 'numpy') f_prime = sp.lambdify(x, f_prime_sym, 'numpy') # 计算导数真实值 true_value = f_prime(x_val) print(f"在x={x_val}处的导数真实值:{true_value}") # 两次输入h计算近似值及误差 prev_approx = None for i in range(2): h_val = float(input(f"请输入第{i+1}个h值:")) approx_value = numerical_derivative(f, x_val, h_val) print(f"用h={h_val}算出的导数近似值:{approx_value}") # 计算真实误差与相对真实误差 true_error = true_value - approx_value relative_true_error = (true_error / true_value) * 100 if true_value != 0 else float('inf') print(f"真实误差:{true_error}") print(f"相对真实误差:{relative_true_error:.2f}%\n") # 计算近似误差(第二次输入h后) if i == 0: prev_approx = approx_value else: if prev_approx is not None: approx_error = prev_approx - approx_value relative_approx_error = (approx_error / approx_value) * 100 if approx_value != 0 else float('inf') print(f"近似误差:{approx_error}") print(f"相对近似误差:{relative_approx_error:.2f}%\n") if __name__ == "__main__": main()
关键调整说明
- 用
sympy库实现符号解析与自动求导,完美支持用户自定义函数输入 - 修正了原代码中数值近似求导的逻辑错误(原代码错误地用了
ggx(x)*ggx(h),正确的向前差分应该是f(x+h)-f(x)除以h) - 增加了输入错误处理,避免无效函数输入导致程序崩溃
- 保留了原有核心流程:两次输入h计算近似值,同时计算真实值、各类误差指标
- 去掉了不必要的
int()强制转换,保留浮点精度,避免误差被无端截断
内容的提问来源于stack exchange,提问作者Ahmad yahya
相关产品推荐
相关产品推荐

