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. bruce wernick 13 years, 10 months ago

This is neat. Could you use this to solve simultaneous equations? Éric Araujo 12 years ago

Wow, talk about a cool recipe! Robin Becker 11 years, 9 months ago

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 11 years, 9 months ago

What is 1j? Robin Becker 11 years, 4 months ago

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)

### Required Modules

• (none specified)