求解多参数方程,选择因变量。 [Python, Scipy]
Solving multiple argument equations, choosing the dependent variable. [Python, Scipy]
我有一些方程式取决于许多变量。我想解 python 中的方程。这是一个更简单的方程式:
f(x,y,theta,w) = x - y + theta * (w - y)
如何 solve/find 给定其余参数的值,为特定变量求出该方程的根。有时我想解决 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
不确定 scipy,但您可能想看看 Sage:
x,y,w,theta = var('x','y','w','theta')
f = x - y + theta * (w - y)
solve(f,x)
[x == -theta*w + (theta + 1)*y]
solve(f,theta)
︡theta == -(x - y)/(w - y)]
我有一些方程式取决于许多变量。我想解 python 中的方程。这是一个更简单的方程式:
f(x,y,theta,w) = x - y + theta * (w - y)
如何 solve/find 给定其余参数的值,为特定变量求出该方程的根。有时我想解决 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
不确定 scipy,但您可能想看看 Sage:
x,y,w,theta = var('x','y','w','theta')
f = x - y + theta * (w - y)
solve(f,x)
[x == -theta*w + (theta + 1)*y]
solve(f,theta)
︡theta == -(x - y)/(w - y)]