ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Linear equations solver in 3 lines
Submitter: Maxim Krikun (other recipes)
Last Updated: 2005/01/31
Version no: 1.1
Category: Programs

 

5 stars 4 vote(s)


Description:

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

Source: Text Source

def solve(eq,var='x'):
    eq1 = eq.replace("=","-(")+")"
    c = eval(eq1,{var:1j})
    return -c.real/c.imag

Discussion:

One could add one more line to insert '*' where needed, i.e. "100x" -> "100*x",
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



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.