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")
3236.0
Python, 4 lines
1
2
3
4
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

3 comments

James Mills 11 years, 1 month ago  # | flag

Nice! ;)

shuoguo 11 years, 1 month ago  # | flag

amazing!

Gabriel Genellina 10 years, 11 months 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