如何在Python程序中使用Mathematica函数?

2024-06-13 08:55:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何从Python调用Mathematica函数。在

我很欣赏一个例子,例如,使用Mathematica函数Prime。在

我曾搜索过MathLink,但如何在Python中使用它对我来说有点模糊。在

我试图使用Mathematica Python库,名为pyml,但没有成功,可能是因为这个库看起来很旧(在教程中说Mathematica 2或3)。在

尝试在Wolfram/Mathematica/8.0/SystemFiles/Links/Python中编译源代码,但在使用Python2.6时出现了几个错误(文档中说应该只适用于Python2.3)。在

Pythonika很有趣,但是,看起来只是在Mathematica笔记本中使用,我想编写调用Mathematica函数的.py文件。在

所以,有人知道编写python程序的好方法,他使用Mathematica函数,可以给我举个例子吗?在


Tags: 函数文档源代码错误笔记本教程linksprime
2条回答

我找到了一个solution。在

步骤:

1-创建一个名为runMath的脚本,其内容如下:

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

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

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

Print[value];

2-我给了文件执行权限。在

^{pr2}$

3-将文件移动到执行路径

sudo mv runMath /usr/bin/

4-创建了一个名为运行的新脚本,内容如下:

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

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

call([command,parameter])

5-移动到执行路径

sudo mv run /usr/bin

6-最后,测试:

$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

可以与'一起使用,也可以不使用。带空格的命令需要'。在

$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}

快乐!在

您可以使用Python MathLink模块(在…/SystemFiles/Links/Python中找到的源代码)在Python中调用Mathematica函数,不过需要编辑几个安装文件才能启动并运行它(support@wolfram.com应该能帮到你)。在

要使用Python中的Prime,可以运行以下命令:

kernel.ready()

0

kernel.putfunction("Prime",1)

kernel.putinteger(10)

kernel.flush()

kernel.ready()

1

kernel.nextpacket()

packetdescriptiondictionary[3]

'返回数据包'

kernel.getinteger()

29岁

相关问题 更多 >