6

I am in the somewhat unfortunate position to try to convert a program from the depths of CERN ROOT to python. In ROOT code (CINT in itself is an abomination imo), one can store mathematical functions as a "string" and pass these along to ROOT for fitting, plotting, etc. because of how ROOT defines these as "strings."

At the moment, the mathematical functions are stored in simple text files as a line, i.e.

(1+[1])^(1+[1])/TMath::Gamma(1+[1]) * x^[1]/[0]^(1+[1]) * exp(-(1+[1])*x/[0])

and are then extracted as strings by C++ when reading in the file. Is there something similar in python? I know of numexpr, but I cant seem to get it to work with the equivalent of the above, i.e.

(1+p[1])**(1+p[1])/scipy.special.Gamma(1+p[1]) * x**p[1]/p[0]**(1+p[1]) * numpy.exp(-(1+p[1])*x/p[0])

Thanks a bunch in advance.

4

1 回答 1

9

因为,大概,您可以相信字符串是非恶意的,您可以构建一个字符串,该字符串定义了一个函数,该函数评估表达式并用于exec将该字符串作为语句执行。例如,

import numpy as np
import scipy.special as special

expr='(1+p[1])**(1+p[1])/special.gamma(1+p[1]) * x**p[1]/p[0]**(1+p[1]) * np.exp(-(1+p[1])*x/p[0])'

def make_func(expr):
    funcstr='''\
def f(x,p):
    return {e}
    '''.format(e=expr)
    exec(funcstr)
    return f

f=make_func(expr)
print(f(1,[2,3]))

返回

0.360894088631
于 2011-12-26T23:37:41.070 回答