Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic algebra in Python
#1
Hi, how can I solve algebraic equations in python?
For example: 100*X=200, which would return 2.
Is there some sort of library for this?
Thanks!
Reply
#2
Take a look at sympy solvers: http://docs.sympy.org/latest/modules/sol...lvers.html

You can download the source to see how they do it: https://github.com/sympy/sympy/releases
Reply
#3
Thanks, I'll give it a try!

When running this code:
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
print solve(x*2 - 5, x).evalf()
it gives this error:
Error:
line 17, in <module> factor = int(next(res.results).text[4:]) ValueError: invalid literal for int() with base 10: '9/40'
How can I get it to return a decimal result?
Reply
#4
Doesn't solve() already return the result?  Why are you eval()ing it?
Reply
#5
It seems to result in the same error whether I eval it or not

But I will remove that from my code
Reply
#6
this code
Quote:
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
print solve(x*2 - 5, x)

does not produce that error for me but the output
Output:
[5/2]
Can you show the entire traceback that you are getting?
Recommended Tutorials:
Reply
#7
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
print solve(x*2 - 5, x)
Output:
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/bin/python2.7 ###########/main.py Traceback (most recent call last): File "###########/main.py", line 17, in <module> factor = int(next(res.results).text[4:]) ValueError: invalid literal for int() with base 10: '9/40' Process finished with exit code 1
To clarify, I am using python 2.7
What I would like it to do would be to output in decimal
As for the different results (and 9/40 makes no sense), maybe this could be due to python2.7?
Reply
#8
Works for me.
It's complaining about line 17 in main.py
Is this your module (main.py)?
if it is, why no line 17?
if not, why no line from your module in traceback?
Reply
#9
What I have posted is my complete script.

What version of python are you using?

Also, I want to thank all of you guys for helping me, earlier I asked a similar question on StackOverflow and it got put on hold because the quality 'wasn't good enough'. Dodgy
Reply
#10
Shouldn't matter, but my code is always done with the latest version which is currently 3.6.2
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020