用IronPython计算C#中的三角函数

2024-06-17 12:08:53 发布

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

我尝试使用Iron Python二进制文件中的Python引擎计算一些与流体力学相关的表达式。我得到了以下密码:

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString("import math", SourceCodeKind.AutoDetect);
source.Execute();
source = engine.CreateScriptSourceFromString("2*sin (2)", SourceCodeKind.AutoDetect);
button1.Text = source.Execute<float>().ToString();

每当我尝试运行时,都会发生以下错误:Global name 'sin' not defined。 我也试过Math.sin(),但没有成功。 有什么想法吗?在


Tags: 文件引擎密码sourceexecute表达式二进制sin
1条回答
网友
1楼 · 发布于 2024-06-17 12:08:53

如果要使所有数学函数在全局范围内可访问(这可能对您很有用,因为表达式本质上是数学的),则可以使用from math import *,而不是{}。

您还应该创建一个ScriptScope来存储全局状态,这样就可以执行多个语句:

ScriptScope scope = engine.CreateScope();

ScriptSource source = engine.CreateScriptSourceFromString("from math import *", SourceCodeKind.AutoDetect);
source.Execute(scope);

source = engine.CreateScriptSourceFromString("2*sin (2)", SourceCodeKind.AutoDetect);
button1.Text = source.Execute<float>(scope).ToString();

您甚至可以将对象从C#放入作用域:

^{pr2}$

相关问题 更多 >