Skip to content

Instantly share code, notes, and snippets.

@goldengrape
Last active January 5, 2024 23:30
Show Gist options
  • Save goldengrape/a232890df5a2be70d07841205116b4b3 to your computer and use it in GitHub Desktop.
Save goldengrape/a232890df5a2be70d07841205116b4b3 to your computer and use it in GitHub Desktop.
用sympy求隐函数二阶导数
from sympy import symbols, Function, Eq,log,solve, simplify
def derivative_hidden_function(equation, x, y_func,N):
# 对方程关于 x 求导,使用链式法则
diff_eq = equation.lhs.diff(x) - equation.rhs.diff(x)
# 解出 dy/dx
dy_dx = solve(diff_eq, y_func.diff(x))[0]
if N==1:
return dy_dx
diy_dxi=dy_dx
# 对 dy/dx 关于 x 求导,使用链式法则
for i in range(N-1):
diy_dxi = diy_dxi.diff(x).subs(y_func.diff(x), dy_dx)
diy_dxi = simplify(diy_dxi)
return simplify(diy_dxi)
# 定义 x 和 y 为符号变量
x = symbols('x')
y = symbols('y', cls=Function)
y = y(x)
# 示例方程
example_equation = Eq(y-2*x, (x-y)*log(x-y))
# 调用函数并显示结果
derivative_hidden_function(example_equation, x, y,3)
@goldengrape
Copy link
Author

这里的关键是要声明y是函数,y=y(x)
y = symbols('y', cls=Function)
y = y(x)

@goldengrape
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment