Type an equation the way you would write it on paper, get the real solutions.
>>> 5*x - 3 = 2*x + 6
Solved: x = 3
>>> x**2 - 5*x + 6 = 0
Solved: x1 = 3, x2 = 2
>>> 2(x - 3) = 4
Solved: x = 5
No eval(), no algebra libraries: a hand-written recursive descent parser turns the equation into a polynomial and solves it.
git clone https://github.com/ParallelNode/xmarks.git
cd xmarks
python linear_eq.pyRequires Python 3.8+. Type an equation and press Enter. Type exit to quit.
| You can use | Example |
|---|---|
+ - * / ^ ** and parentheses |
(x - 1)*(x - 2) = 0 |
| Implicit multiplication | 2x + 4 = 0, 2(x - 3) = 4 |
| Division by a number | x/2 = 3 |
| Integer powers, 0 to 100 | x**2 - 4*x + 4 = 0 |
| Unary minus | -(3x + 2) = 4, -x^2 = -4 |
Possible results: one value, two values, No solution, Infinite solutions, No real solutions.
Type file at the prompt, then the path of a text file with one equation per line. Blank lines and lines starting with # are ignored.
equations.txt
# my equations
2x + 4 = 0
x/2 = 3
x**2 + x + 1 = 0
>>> file
filepath>>> equations.txt
2x + 4 = 0 -> x = -2
x/2 = 3 -> x = 6
x**2 + x + 1 = 0 -> No real solutions
A wrong line shows an error and the rest still run.
text → tokenizer → recursive descent parser → polynomial → solver
"3x+2=8" [3, x, +, 2] expr → term → unary → power → factor {1: 3, 0: -6} x = 2
Every polynomial is a dictionary {degree: coefficient}. Everything on the right of the = is moved to the left, then the equation is solved directly (1st degree) or with the discriminant (2nd degree).
| Code | Cause | Example |
|---|---|---|
Error0 |
no = |
x + 1 |
Error1 |
degree above 2, or division by x |
x**3 + x = 0 |
Error2 |
invalid character | 3x + $ = 4 |
Error3 |
more than one = |
x + 1 == 0 |
Error4 |
variable other than x |
y + 1 = 0 |
- Only the unknown
x - Only real solutions
- Up to degree 2
- Equations are typed at the prompt or read from a file (not passed as command-line arguments)
Optional banner
On startup the program can show a colored braille-art banner made by banner_gen.py. It needs:
pip install pillow numpyand an image named images.jpg next to the scripts (not included). Without them the program works the same and prints a short warning.
banner_gen.py also works on its own:
python banner_gen.py picture.jpg -w 100 --mode combo --color