python eval()函数的错误结果

时间:2019-06-19 16:08:26

标签: python

我有一个应该计算黎曼和的函数,这里是:

import sympy as sym

x = sym.Symbol('x')

def left_riemann_sum(f, lower_bound, list):
    area = 0
    cur_val = lower_bound
    for x in list:
        height = eval(f(cur_val))
        width = x - cur_val
        print("cal area for height: " + str(height) + " and width: " + str(width))
        area = area + height * width
        cur_val = x

    return area

问题是eval(f(cur_val))的值有误 使用以下参数运行此功能时:

print('left sum: ' + str(left_riemann_sum(f1, 3, [6.5, 10])))

并为此功能:

def f1(x):
    return '-10*x**2+3*x+6'

显示高度为:-397和-964,而应该为-75和-397。看来它跳过了第一次运行,所以我无法弄清楚。

2 个答案:

答案 0 :(得分:2)

将函数定义为表达式,而不是将函数定义为strings

def f1(x):
    return -10*x**2+3*x+6

那么您的身高将计算为:

height = f(cur_val)

这样最终的代码将是:

import sympy as sym

x = sym.Symbol('x')

def left_riemann_sum(f, lower_bound, list):
    area = 0
    cur_val = lower_bound
    for x in list:
        height = f(cur_val)
        width = x - cur_val
        print("cal area for height: " + str(height) + " and width: " + str(width))
        area = area + height * width
        cur_val = x

    return area

def f1(x):
    return -10*x**2+3*x+6

print('left sum: ' + str(left_riemann_sum(f1, 3, [6.5, 10])))

输出

cal area for height: -75 and width: 3.5
cal area for height: -397.0 and width: 3.5
left sum: -1652.0

如果您确实要使用eval()

您做错了。首先按照上面的定义函数,返回一个表达式:

def f1(x):
    return -10*x**2+3*x+6

然后您可以使用以下方法计算高度:

height = eval('f(cur_val)')

答案 1 :(得分:-1)

如果要获取符号解决方案,可以定义3个符号x y h并将其传递给left_riemann_sum函数,

x, y, h = sym.symbols('x y h')
print('left sum: ' + str(left_riemann_sum(f1, h, [x, y])))

然后这就是输出

cal area for height: -10*h**2 + 3*h + 6 and width: -h + x
cal area for height: -10*x**2 + 3*x + 6 and width: -x + y
left sum: (-h + x)*(-10*h**2 + 3*h + 6) + (-x + y)*(-10*x**2 + 3*x + 6)

这是其余的代码,

import sympy as sym

def left_riemann_sum(f, lower_bound, list):
    area = 0
    cur_val = lower_bound
    for y in list:
        height = f(cur_val)
        width = y - cur_val
        print("cal area for height: " + str(height) + " and width: " + str(width))
        area = area + height * width
        cur_val = y

    return area

def f1(x):
    return -10*x**2+3*x+6