Python: How to evaluate a function which is string?

前端 未结 5 1960
悲&欢浪女
悲&欢浪女 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:43

    If you want to parse the 'function' string, you could do something like this:

    import re
    
    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;"
    
    def f(t):
        l = map(float, re.findall("-?\\d+\\.\\d+", s))
        return sum(b * t**a for a,b in enumerate(l))
    
    print map(f, xrange(1,13))
    
    [239.75206957484252, 544.337732955938, 921.544112756058, 1366.6221363666925, 1864.8848673959649, 2393.2591324279497, 2922.9192385578326, 3423.0027817028927, 3865.4085456893295, 4230.676492114911, 4514.949840987468, 4738.019242139209]
    

    This approach assumes that the function string will always be of the form

    c0 + c1 t + c2 t^2 + c3 t^4 + ... cn t^(n+1)
    

    and works by extracting the floating point numbers from the string and using them to generate an actual Python function.

提交回复
热议问题