use*_*074 5 python scipy equation-solving
我有一些方程式取决于许多变量。我想解决python中的方程式。这是更简单的方程式之一:
f(x,y,theta,w) = x - y + theta * (w - y)
在给定其余参数的值的情况下,如何解决/找到特定变量的方程式的根。有时候我想解决x,有时候我想解决theta。
有没有一种优雅的方法可以解决此问题而不必为每个因变量重写函数?
看看 python 库Sympy。这是一个示例 Jupyter 笔记本会话。
In [71]: from sympy import *
In [72]: w, x, y, theta = symbols('w x y theta') # define symbols
In [75]: func = x - y + theta * (w - y) # define function
In [76]: solve(func, x) # algebraic solution for x
Out[76]: [-theta*w + theta*y + y]
In [77]: solve(func, theta) # algebraic solution for theta
Out[77]: [(-x + y)/(w - y)]
In [81]: func2 = func.subs([(w,2.0), (y,0.5), (theta,3.14)])
In [82]: func2 # substitute for some variables
Out[82]: x + 4.21
In [83]: a = np.arange(5)
f = lambdify(x, func2, "numpy") # convert to a func to use with numpy
f(a)
Out[83]: array([ 4.21, 5.21, 6.21, 7.21, 8.21]) # apply to numpy array
In [84]: func2.evalf(subs={x:33}) # evaluate
Out[84]: 37.2100000000000
Run Code Online (Sandbox Code Playgroud)