Welcome, guest | Sign In | My Account | Store | Cart

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")
Python, 4 lines
def solve(eq,var='x'):
    eq1 = eq.replace("=","-(")+")"
    c = eval(eq1,{var:1j})
    return -c.real/c.imag

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


James Mills 10 years, 3 months ago  # | flag

Nice! ;)

shuoguo 10 years, 2 months ago  # | flag


Gabriel Genellina 10 years ago  # | flag

Did you intend to make a fork? I don't see any change from the original recipe.

Created by Deepak on Thu, 7 Mar 2013 (PSF)
Python recipes (4591)
Deepak's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks