Skip to content

Commit

Permalink
Implement ComplexExpand
Browse files Browse the repository at this point in the history
Clean up ComplexExpand

Added test cases for ComplexExpand

Fix style
  • Loading branch information
yzrun committed Jul 4, 2023
1 parent a2e9267 commit 10dab5c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions mathics/builtin/numbers/hyperbolic.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ class ComplexExpand(SympyFunction):
sympy_name = "expand"

def eval(self, expr, evaluation: Evaluation):
"ComplexExpand[expr_]"
return eval_ComplexExpand(expr, ListExpression())

def eval_with_complex_vars(self, expr, vars, evaluation: Evaluation):
Expand Down
11 changes: 10 additions & 1 deletion mathics/eval/hyperbolic.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
"""
Mathics3 builtins from mathics.core.numbers.hyperbolic
"""
from sympy import Symbol as SympySymbol

from mathics.core.convert.sympy import from_sympy


def eval_ComplexExpand(expr, vars):
sympy_expr = expr.to_sympy()
# Turn Re[x] -> x and remove Im[x] for all variables X that are not in vars.
sympy_vars = {v.to_sympy() for v in vars.elements}
# All vars are assumed to be real
replaces = [
(fs, SympySymbol(fs.name, real=True))
for fs in sympy_expr.free_symbols
if fs not in sympy_vars
]
sympy_expr = sympy_expr.subs(replaces)
return from_sympy(sympy_expr.expand(complex=True))
11 changes: 11 additions & 0 deletions test/builtin/numbers/test_hyperbolic.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,14 @@ def test_gudermannian():
("Gudermannian[z]", "2 ArcTan[Tanh[z / 2]]"),
):
check_evaluation(str_expr, str_expected)


def test_complexexpand():
for str_expr, str_expected in (
("ComplexExpand[Sin[x + I y]]", "Cosh[y]*Sin[x] + I*Cos[x]*Sinh[y]"),
(
"ComplexExpand[3^(I x)]",
"3 ^ (-Im[x]) Re[3 ^ (I Re[x])] + I Im[3 ^ (I Re[x])] 3 ^ (-Im[x])",
),
):
check_evaluation(str_expr, str_expected)

0 comments on commit 10dab5c

Please sign in to comment.