Python: How to evaluate a function which is string?

前端 未结 5 1961
悲&欢浪女
悲&欢浪女 2021-01-16 23:22

I get some models from database as

f(t)=(2.128795454425367)+(208.54359721863273)*t+(26.098128487929266)*t^2+(3.34369909584111)*t^3+(-0.3450228278737971)*t^4+         


        
5条回答
  •  执念已碎
    2021-01-16 23:42

    If performance isn't a major concern -- and if you're only evaluating it at 12 points, I suspect it's not -- then you can leverage the handy sympy library to do a lot of the work for you. For example:

    >>> import sympy
    >>> sympy.sympify("t**5 - t + 3")
    t**5 - t + 3
    >>> sympy.sympify("t**5 - t + 3").subs({"t": 10})
    99993
    

    We can wrap this up in a function which returns a function:

    import sympy
    
    def definition_to_function(s):
        lhs, rhs = s.split("=", 1)
        rhs = rhs.rstrip('; ')
        args = sympy.sympify(lhs).args
        f = sympy.sympify(rhs)
        def f_func(*passed_args):
            argdict = dict(zip(args, passed_args))
            result = f.subs(argdict)
            return float(result)
        return f_func
    

    which we can then apply, even to more complex cases beyond the easy reach of regex:

    >>> s = "f(t)=(2.128795454425367)+(208.54359721863273)*t+(26.098128487929266)*t^2+(3.34369909584111)*t^3+(-0.3450228278737971)*t^4+(-0.018630757967458885)*t^5+(0.0015029038553239819)*t^6;"
    >>> f = definition_to_function(s)
    >>> f(0)
    2.128795454425367
    >>> f(10)
    4230.6764921149115
    >>> f = definition_to_function("f(a,b,c) = sin(a)+3*b-4*c")
    >>> f(1,2,3)
    -5.158529015192103
    >>> import math
    >>> math.sin(1)+3*2-4*3
    -5.158529015192103
    

提交回复
热议问题