如何用Python求解二项式导数及sympy代码报错处理
问题根源
- 你定义的
f(x)返回的是SymPy的符号表达式,而scipy.misc.derivative要求入参函数必须输入数值返回数值,类型不匹配触发报错 - 重复调用符号求导逻辑冗余,且用数值求导计算已经有解析解的导数完全没有必要,反而会带来精度误差
- 没有预留自定义求导点的输入入口,硬编码的2.0不符合你需要指定x取值的需求
修复后完整代码
import sympy as sp # 定义符号变量 x = sp.Symbol("x") # 收集用户输入 sign = input("What is the operator of the equation? ") a = int(input("What is the value of a? ")) expo = int(input("What is the value of exponent for x? ")) b = int(input("What is the value of b? ")) x_val = int(input("What is the value of x to calculate derivative? ")) # 构造原二项式 if sign == '-': original_expr = a * x ** expo - b elif sign == '+': original_expr = a * x ** expo + b else: raise ValueError("Only support '+' or '-' as operator") # 计算导函数 deriv_expr = sp.diff(original_expr, x) # 输出导函数 print(f"f'(x) = {deriv_expr}") # 代入指定x值计算导数值 deriv_value = deriv_expr.subs(x, x_val) # 输出导数值 print(f"The derivative value at x={x_val} is {deriv_value}")
验证效果
输入示例:
What is the operator of the equation? - What is the value of a? 6 What is the value of exponent for x? 2 What is the value of b? 2 What is the value of x to calculate derivative? 3
输出结果:
f'(x) = 12*x The derivative value at x=3 is 36
完全符合你的需求。
内容的提问来源于stack exchange,提问作者Maneki Autumn
相关产品推荐
相关产品推荐

