python eval()函数的结果错误
我有一个函数,用来计算黎曼和,这里是:python eval()函数的结果错误,python,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
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
问题是evalfcur_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。看起来它跳过了第一次运行,我想不出来。如果你想得到一个符号解,你可以定义3个符号x y h,然后像这样传递给左黎曼和函数 x、 y,h=符号'x y h' 打印“左和:”+strleft\u riemann\u sumf1,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)
下面是代码的其余部分
将sympy作为sym导入
def left_riemann_sumf,下界,列表:
面积=0
cur_val=下限
对于列表中的y:
高度=fcur_val
宽度=y-当前值
高度的打印校准区域:+strheight+和宽度:+strwidth
面积=面积+高度*宽度
cur_val=y
返回区
def f1x:
返回-10*x**2+3*x+6
不要将函数定义为字符串,而是将其定义为表达式:
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])))
输出
如果你真的,真的想用eval
你做错了。首先,如上所述定义函数,返回表达式:
def f1(x):
return -10*x**2+3*x+6
然后,可以使用以下公式计算高度:
height = eval('f(cur_val)')
为什么要对一个包含字符串的函数使用eval,而不是一个包含表达式的正则函数?啊,对不起,我的错。我忽略了eval。我现在提出了另一种解决方案。谢谢
height = eval('f(cur_val)')