如何将用户输入用作数字积分算法的函数?

问题描述

我发现了一种算法,该算法使用黎曼和(也称为矩形近似)来计算函数曲线下的面积。但是,每次我要计算其他函数时,都必须更改算法内部的函数。在下面的代码中,该算法已设置为计算x**2曲线下的面积。

# Calcuate the area under a curve
#
# Example Function y = x^2
#
# This program integrates the function from x1 to x2
# x2 must be greater than x1,otherwise the program will print an error message.
#
x1 = float(input(’x1=’))
x2 = float (input(’x2=’))
if x1 > x2:
    print(’The calculated area will be negative’)
# Compute delta_x for the integration interval
#
delta_x = ((x2-x1)/1000)
j = abs ((x2-x1)/delta_x)
i = int (j)
print(’i =’,i)
# initialize
n=0
A= 0.0
x = x1
# Begin Numerical Integration
while n < i:
    delta_A = x**2 * delta_x
    x = x + delta_x
    A = A + delta_A
    n = n+1
print(’Area Under the Curve =’,A)

我尝试让用户输入一个函数,比如说exp((x** 2)-x) * sin(x**3)x1 = 1x2 = 2.5,但是它不起作用,它显示无效语法的错误消息。使用eval(input(...))方法进行了尝试并进行了计算,但是给出了错误的答案(1.2612 ...)。这个问题的正确答案是2.397 ...

在算法中必须重写功能是一种不便,对用户而言并不实用。

有人可以帮我吗?

解决方法

正如@Tarik所说,请首先检查代码的逻辑。

然后尝试eval(),例如:

x1=1
x2=2.5
Area under the curve 2.395500858985482

示例I / O:

{{1}}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...