You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:18:01