gpt4 book ai didi

python - 在 C++ 中高效地执行数学 Python 表达式

转载 作者:行者123 更新时间:2023-11-30 05:42:48 25 4
gpt4 key购买 nike

我有一个 python 程序,它生成一个像

这样的数学表达式
exp(sin(x-y))**2

现在我想把它交给我的 C++ 程序,它必须用不同的 x,y 值计算这个表达式。我的第一种方法是将 Python.h 库与 PyRun_String 一起使用。

这里是初始化代码:

func=function;
Py_Initialize();
memset(pythonString,0,strlen(pythonString));

// add whiteNoise Kernel
sprintf(pythonString,"from math import *;func=lambda x,y:(%s+0.1*(x==y))",function);
//printf("%s\n",pythonString);
PyRun_SimpleString(pythonString);

这里是多次求值的代码:

char execString[200];
memset(execString,0,strlen(execString));

sprintf(execString,"result=func(%f,%f)",x1[0], x2[0]);

PyObject* main = PyImport_AddModule("__main__");
PyObject* globalDictionary = PyModule_GetDict(main);
PyObject* localDictionary = PyDict_New();

//create the dictionaries as shown above

PyRun_String(execString, Py_file_input, globalDictionary, localDictionary);
double result = PyFloat_AsDouble(PyDict_GetItemString(localDictionary, "result"));

不过,我觉得每次都用PyRun_String来解析字符串真的太慢了​​。有没有一种方法可以直接将 Python 表达式转换为可以有效调用的 C++ 函数?还是有其他选择?也可以使用类似 symbolicc++ 的东西

最佳答案

我建议将您的所有输入作为数组/vector 传递给您的 C++ 并立即解决所有问题。另外,尝试使用 Py_CompileStringPyEval_EvalCode 而不是 PyRun_String。我必须求解数百万个方程,并发现速度提高了 10 倍。

下面是一个简单的 'a + b' 示例,但通过更多的 for 循环,可以将其推广到具有任意数量变量的任何方程式。对于下面的一百万个值,在我的机器上用不到一秒的时间就完成了(与 PyRun_String 的 10 秒相比)。

PyObject* main = PyImport_AddModule("__main__");
PyObject* globalDict = PyModule_GetDict(main);
PyCodeObject* code = (PyCodeObject*) Py_CompileString("a + b", "My Eqn", Py_eval_input);
for (millions of values in input) {
PyObject* localDict = PyDict_New();
PyObject* oA = PyFloat_FromDouble(a); // 'a' from input
PyObject* oB = PyFloat_FromDouble(b); // 'b' from input
PyDict_SetItemString(localDict, "a", oA);
PyDict_SetItemString(localDict, "b", oB);
PyObject* pyRes = PyEval_EvalCode(code, globalDict, localDict);
r = PyFloat_AsDouble(pyRes);
// put r in output array

Py_DECREF(pyRes);
Py_DECREF(localDict)
}
Py_DECREF(code);

关于python - 在 C++ 中高效地执行数学 Python 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30507347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com