Welcome, guest | Sign In | My Account | Store | Cart
NOTE: Recipes have moved! Please visit GitHub.com/activestate/code for the current versions.

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

5 comments

bruce wernick 8 years, 6 months ago  # | flag

This is neat. Could you use this to solve simultaneous equations?

√Čric Araujo 6 years, 8 months ago  # | flag

Wow, talk about a cool recipe!

Robin Becker 6 years, 5 months ago  # | flag

This fails if c.imag is zero eg

print solve("x=1j") Traceback (most recent call last): File "C:\Tmp\solvelin.py", line 9, in <module> print solve("x = 1j") File "C:\Tmp\solvelin.py", line 4, in solve return -c.real/c.imag ZeroDivisionError: float division

another example is "x=1+1j"

Jamison White 6 years, 4 months ago  # | flag

What is 1j?

Robin Becker 5 years, 11 months ago  # | flag

Well j is the square root of -1 and as python supports complex numbers and we learn to solve quadratics with complex roots a linear equation solver ought to handle complex coefficents.

Created by Maxim Krikun on Sat, 29 Jan 2005 (PSF)
Python recipes (4591)
Maxim Krikun's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks