Is there a way to convert simple python code to Mathematica code
Asked
Active
Viewed 2,127 times
7
-
Is "Simpyle" a typo, or is it something in the Python world I should know about? – ktm Feb 10 '20 at 01:31
-
You can also evaluate Python code in Mathematica using > at the beginning of a cell ( https://www.wolfram.com/language/12/external-system-integration/evaluate-python-in-a-notebook.html?product=language ) or using ExternalEvaluate as shown here: https://reference.wolfram.com/language/ref/externalevaluationsystem/Python.html and https://reference.wolfram.com/language/workflow/ExecuteAPythonFileWithExternalEvaluate.html – userrandrand Apr 24 '23 at 16:47
2 Answers
15
I do not think there is general way to convert large chunk of code from Python to Mathematica (such as complete functions). But for individual expressions you could try this do it via Latex.
In Python
In[24]: from sympy import *
In[25]: x,y=symbols('x y')
In[26]: expr= 1+2**(x+y)*integrate(sin(x),x)-2*tan(x)
In[27]: expr
Out[27]: -2**(x + y)*cos(x) - 2*tan(x) + 1
In[28]: sympy.latex(expr)
Out[28]: '- 2^{x + y} \\cos{\\left(x \\right)} - 2 \\tan{\\left(x \\right)} + 1'
Now transfer the last expression to Mathematica. You could do this via file, or manually, or in other ways. Once inside Mathematica, then type
expr = "-2^{x+y} \\cos{\\left(x \\right)}-2 \\tan{\\left(x \\right)}+1";
ToExpression[expr, TeXForm]
Which gives
1+(-2)^(x+y) Cos[x]-2 Tan[x]

Nasser
- 143,286
- 11
- 154
- 359
1
https://docs.sympy.org/latest/modules/printing.html#module-sympy.printing.mathematica
example:
from sympy import integrate, sin, tan, mathematica_code
from sympy.abc import x, y
print(mathematica_code((1 + 2 ** (x + y) * integrate(sin(x), x) - 2 * tan(x))))
get
-2^(x + y)*Cos[x] - 2*Tan[x] + 1
All supported functions are here, sympy.printing.mathematica.known_functions
AsukaMinato
- 9,758
- 1
- 14
- 40