Sapiens Search

Showing posts with label Mathematica. Show all posts
Showing posts with label Mathematica. Show all posts

How to run Mathematica functions on Python?

1-Create a script named runMath with the content:

    #!/usr/local/bin/MathematicaScript -script

    value=ToExpression[$ScriptCommandLine[[2]]];

    (*The next line prints the script name.*)
    (*Print[$ScriptCommandLine[[1]]];*)

    Print[value];

2-Give execution privilege to the file:
    sudo chmod +x runMath

3-Move the file to the execution path:

    sudo mv runMath /usr/bin/

4-Create a new script called run with the content:

    #!/usr/bin/python
    from subprocess import *
    from sys import *

    command='/usr/bin/runMath'
    parameter=argv[1]

    call([command,parameter])

5-Move to the execution path:

    sudo mv run /usr/bin

6-Finally, test it:

    $run Prime[100]
    541

    $run 'Sum[2x-1,{x,1,k}]'
    k^2

    $run Integrate[Log[x],x]
    -x + x*Log[x]

    $run 'Zeta[2]'
    Pi^2/6

You can use with ou without '. The ' are needed to commands with spaces.

    $run 'f[n_] := f[n] = f[n - 1] + f[n - 2]; f[1] = f[2] = 1; Table[f[n],{n,5}]'
    {1, 1, 2, 3, 5}