5

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, sometimes I want to solve for theta.

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

user668074
  • 1,111
  • 10
  • 16
  • Possible duplicate of [python solving equations for unknown variable](http://stackoverflow.com/questions/10274236/python-solving-equations-for-unknown-variable) – Reti43 Feb 10 '16 at 23:41
  • Are you looking for an analytical or numerical solution? In the latter case, you can use scipy solvers with a lambda to forward/reorder arguments as needed. – ev-br Feb 11 '16 at 09:19

2 Answers2

5

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
RootTwo
  • 4,288
  • 1
  • 11
  • 15
1

Not sure about scipy, but you might want to have a look at 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)]
maxymoo
  • 35,286
  • 11
  • 92
  • 119