I obtain a raw input form of:

(1.*(43.013537902165325 + 43.013537902165346*E^(0.003288590604026849*t))^2)/
   (3700.328885722024 + 5.4569682106375694*^-12*E^(0.003288590604026849*t) + 

This is just one of the large lists of expression.

How can I convert mathematica math expression to python math expression?

  • $\begingroup$ The other big issue is clearly the math.sin() and all that in place of Sin[] $\endgroup$ – Rho Phi Aug 10 '16 at 15:53

FortranForm gets you close. ( Fortran and Python use the same syntax for most things )

    pw = PageWidth /. Options[$Output];
    SetOptions[$Output, PageWidth ->Infinity];
    FortranForm[ expression  /. E^x_ :> exp[x] ]
    SetOptions[$Output, PageWidth -> pw];

(1.*(43.013537902165325 + 43.013537902165346*exp(0.003288590604026849*t))**2)/(3700.328885722024 + 5.4569682106375694e-12*exp(0.003288590604026849*t) + 3700.328885722026*exp(0.006577181208053698*t))

note we need to set pagewidth because you sure don't want Fortran continuation marks. The E^x_ replacement puts the exponential into python form, you will need to do similar with other functions.

One thing to be careful about, if you have integer rationals in your mathematica expression they give you integer arithmetic in python, which is not likely what you want. In that case you can apply N to the whole works, although that can have other issues.

Edit, refinement:

 FortranForm[ expression  //. {1. y_ -> y, E^x_ -> exp[x]  }]

gets rid of the superfluous 1. multipliers.

  • $\begingroup$ Many thanks. I have a further question. How to convert 1.? $\endgroup$ – Ka-Wa Yip Jun 8 '15 at 15:37
  • 1
    $\begingroup$ I'm not sure what you mean by convert 1.. Do you want the floating 1. to appear as an integer? $\endgroup$ – george2079 Jun 8 '15 at 16:52
  • 1
    $\begingroup$ (1) I think you should use RuleDelayed in your refinement. (2) You may find x_Real y_ /; x == 1 :> y more robust. $\endgroup$ – Mr.Wizard Jun 8 '15 at 23:24

Maybe you could convert expressions from mathematica to latex then use Latex Lambda to get back the python function. Latex Lambda converts latex math notation to lambda functions in Python. So you would input mathematica converted latex expressions and get back the python function.





    "func":"lambda n,ß,α: np.prod([(np.arcsin(α)*np.sin(ß))/(np.sqrt(α*ß)) for i in range(int(1),int(n)+1)])",
    "params":["n", "ß", "α"]


>>> import numpy as np
>>> func = lambda n,ß,α: np.prod([(np.arcsin(α)*np.sin(ß))/(np.sqrt(α*ß)) for i in range(int(1),int(n)+1))])
>>> func(4,1,1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.