From 55df0bd2ab05ecbd39dac827af827dd7dadb4923 Mon Sep 17 00:00:00 2001 From: Idan Pazi Date: Fri, 8 Mar 2024 09:24:24 +0200 Subject: [PATCH] formatter expr add simplify for expressions like (1+i)*(1-i) --- calcpy/formatters.py | 2 ++ calcpy/tests/test_formatters.py | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/calcpy/formatters.py b/calcpy/formatters.py index a29557c..e9546a1 100644 --- a/calcpy/formatters.py +++ b/calcpy/formatters.py @@ -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 diff --git a/calcpy/tests/test_formatters.py b/calcpy/tests/test_formatters.py index f62e41f..0ef4def 100644 --- a/calcpy/tests/test_formatters.py +++ b/calcpy/tests/test_formatters.py @@ -1,5 +1,8 @@ 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' @@ -7,3 +10,10 @@ def test_unicode_power(ip): 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