Skip to content

Commit

Permalink
evalf bug fix - support matrices
Browse files Browse the repository at this point in the history
  • Loading branch information
idanpa committed Mar 15, 2024
1 parent 806bfbb commit a718eed
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
14 changes: 10 additions & 4 deletions calcpy/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,13 @@ def pretty_stack(str1, relation, str2, num_columns):
sp2 = stringPict(*sp2.left(relation))
return stringPict(*sp1.right(sp2)).render(wrap_line=True, num_columns=num_columns)

def evalf(expr:sympy.Expr):
def evalf(expr):
calcpy = IPython.get_ipython().calcpy
expr = expr.doit()
if expr.free_symbols:
if calcpy.auto_evalf:
expr = expr.doit()
if isinstance(expr, sympy.matrices.MatrixBase):
return expr.applyfunc(evalf)
elif expr.free_symbols:
if expr.is_polynomial() and calcpy.auto_expand_factor_poly:
expand = expr.expand()
if expand == expr:
Expand All @@ -130,8 +133,11 @@ def evalf(expr:sympy.Expr):
return expr.simplify()
return factor
return expand
elif expr.is_rational_function():
return expr.simplify()
return expr
expr = expr.simplify()
else:
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
Expand Down
4 changes: 3 additions & 1 deletion calcpy/tests/test_formatters.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sympy.abc import x, y
from sympy import I as i
from sympy import Rational
from sympy import Rational, Matrix
from IPython.lib.pretty import pretty
from calcpy.formatters import evalf

Expand All @@ -17,3 +17,5 @@ def test_evalf(ip):
assert evalf((i+1)*(i-1)) == -2
assert evalf((i+1)/(i-1)) == -i
assert evalf(Rational(1,2)) == 0.5
assert evalf(Matrix(((x**2+2*x+1, Rational(1,2)),))) == Matrix((((x+1)**2, 0.5),))

0 comments on commit a718eed

Please sign in to comment.