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
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
This is neat. Could you use this to solve simultaneous equations?
Wow, talk about a cool recipe!
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"
What is 1j?
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.