【发布时间】:2020-12-05 12:34:17
【问题描述】:
我找到了一种算法,它使用黎曼和(也称为矩形近似)来计算函数曲线下的面积。但是,每次我想计算不同的函数时,我都必须更改算法内部的函数。在下面的代码中,算法设置为计算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)
我试过要求用户输入一个函数,比如从x1 = 1 到x2 = 2.5 的exp((x** 2)-x) * sin(x**3),但它不起作用,它显示无效语法的错误消息。尝试使用 eval(input(...)) 方法并进行计算,但它给出了错误的答案(1.2612 ...)。这个问题的正确答案是 2.397...
在算法中重写函数很不方便,对用户来说不实用。
谁能帮帮我?
【问题讨论】:
-
显示不起作用的代码。你确定你用来集成的代码是正确的吗?请注意,scipy 包有现成的和经过测试的更准确的集成功能。
-
也可以使用sympy解析:docs.sympy.org/latest/modules/parsing.html
-
感谢@Tarik 关于使用 SciPy 的建议,我不知道。这对我很有用。
-
也看看 sympy。
标签: python math numerical-methods numerical-integration calculus