Skip to content

Instantly share code, notes, and snippets.

@simonLeary42
Last active November 3, 2023 06:29
Show Gist options
  • Save simonLeary42/96311225259111f7dd5e2c46d78eba2c to your computer and use it in GitHub Desktop.
Save simonLeary42/96311225259111f7dd5e2c46d78eba2c to your computer and use it in GitHub Desktop.
simplify math expressions with sympy
import sympy
import readline # allow arrow keys while typing inputs
while True:
expression = input("expression: ")
unknowns = input("unknowns comma delimited: ")
exec_str = f"{unknowns} = sympy.symbols(\"{unknowns}\")"
print(f"> {exec_str}")
exec(exec_str)
exec_str = f"expr = {expression}"
print(f"> {exec_str}")
exec(exec_str)
print(f"> expr.simplify()")
print(expr.simplify())
print()
@simonLeary42
Copy link
Author

simonLeary42 commented Nov 3, 2023

expression: (s+0.4)*(s**2-0.36*s+0.16)*(s+9)+25*(s+0.03)*(0.71)*(s+1)
unknowns comma delimited: s
> s = sympy.symbols("s")
> expr = (s+0.4)*(s**2-0.36*s+0.16)*(s+9)+25*(s+0.03)*(0.71)*(s+1)
> expr.simplify()
1.0*s**4 + 9.04*s**3 + 18.126*s**2 + 18.4905*s + 1.1085

user input was on the first 2 lines, nowhere else

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment