user668074 - 1 year ago 34

Python Question

I have some equations that depend on a number of variables. I would like to solve the equations in python. Here is one of the simpler equations:

`f(x,y,theta,w) = x - y + theta * (w - y)`

How can I solve/find the roots of this equation for a particular variable, given values for the rest of the arguments. Sometimes I want to solve for

`x`

`theta`

Is there an elegant way of solving this without having to rewrite the function for each dependant variable?

Answer

Take a look at the python library Sympy. Here's a sample Jupyter notebook session.

```
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
```

Source (Stackoverflow)