Python 如何使用用户输入作为数值积分算法的函数?

Python 如何使用用户输入作为数值积分算法的函数?,python,math,numerical-methods,numerical-integration,calculus,Python,Math,Numerical Methods,Numerical Integration,Calculus,我发现了一种算法,它使用黎曼和(也称为矩形近似)计算函数曲线下的面积。然而,每当我想计算一个不同的函数时,我必须改变算法中的函数。在下面的代码中,算法设置为计算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 t

我发现了一种算法,它使用黎曼和(也称为矩形近似)计算函数曲线下的面积。然而,每当我想计算一个不同的函数时,我必须改变算法中的函数。在下面的代码中,算法设置为计算
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)
#计算曲线下的面积
#
#示例函数y=x^2
#
#该程序集成了从x1到x2的功能
#x2必须大于x1,否则程序将打印错误消息。
#
x1=浮点(输入('x1='))
x2=浮动(输入('x2='))
如果x1>x2:
打印('计算面积为负数')
#计算积分间隔的delta_x
#
δx=((x2-x1)/1000)
j=abs((x2-x1)/delta_x)
i=int(j)
打印('i=',i)
#初始化
n=0
A=0.0
x=x1
#开始数值积分
而n

显示不起作用的代码。您确信用于集成的代码是正确的吗?请注意,scipy软件包已经准备好并测试了更精确的集成功能。您也可以使用sympy解析:感谢@Tarik提供关于使用scipy的建议,我不知道。这将对我非常有用。也可以看看sympy。非常感谢您抽出时间。我会按照塔里克的建议去做的,那个笨蛋。我不知道那个科学的东西,它对微积分、工程和科学都非常有用。我会坚持使用它的文档,我相信它会非常有用。再次感谢。
x1=1
x2=2.5
Area under the curve 2.395500858985482