Skip to content

Commit

Permalink
formatter expr add simplify
Browse files Browse the repository at this point in the history
for expressions like (1+i)*(1-i)
  • Loading branch information
idanpa committed Mar 8, 2024
1 parent 954e9b6 commit 55df0bd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
2 changes: 2 additions & 0 deletions calcpy/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,10 @@ def evalf(expr:sympy.Expr):
return factor
return expand
return expr
expr = expr.simplify()
types = set(map(type, expr.atoms(sympy.Rational, sympy.Function, sympy.NumberSymbol, ExprWithLimits)))
types -= {sympy.Integer, sympy.core.numbers.Zero, sympy.core.numbers.One, sympy.core.numbers.NegativeOne}
# call evalf only when needed - fractions, functions (e.g. trigonometric), constants (e.g. pi) or limits
if calcpy.auto_evalf and types:
return expr.evalf(chop=calcpy.chop, n=15)
return expr
Expand Down
10 changes: 10 additions & 0 deletions calcpy/tests/test_formatters.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
from sympy.abc import x, y
from sympy import I as i
from sympy import Rational
from IPython.lib.pretty import pretty
from calcpy.formatters import evalf

def test_unicode_power(ip):
assert pretty(x**3+2*x**2+3) == 'x³ + 2⋅x² + 3'
assert pretty(x**-1) == 'x⁻¹'
assert pretty((x+y)**-1) == '(x + y)⁻¹'
assert pretty((x+y/5)**-2) == '(x + y/5)**(-2)'
assert pretty((x/y)**-2) == 'y**2/x**2'

def test_evalf(ip):
assert evalf(x**2+2*x+1) == (x+1)**2
assert evalf((x+1)**2) == x**2+2*x+1
assert evalf((i+1)*(i-1)) == -2
assert evalf((i+1)/(i-1)) == -i
assert evalf(Rational(1,2)) == 0.5

0 comments on commit 55df0bd

Please sign in to comment.