ActiveState Code

Recipe 365013: Linear equations solver in 3 lines


Just a little bit of hack: a linear equations solver using eval and built-in complex numbers:

>>> solve("x - 2*x + 5*x - 46*(235-24) = x + 2")
3236.0
Python
1
2
3
4
def solve(eq,var='x'):
    eq1 = eq.replace("=","-(")+")"
    c = eval(eq1,{var:1j})
    return -c.real/c.imag

Discussion

One could add one more line to insert '' where needed, i.e. "100x" -> "100x", add some input validation, in particular check whether the equation is actually linear and not quadratic or cubic, and finally add a GUI to solve and plot multiple linear functions using different colors and get a nice tool for use in elementary mathematical education.

See also "Manipulate simple polynomials in Python" by Rick Muller http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362193

Sign in to comment