【问题标题】:How to use user input as the function for a numeric integration algorithm?如何使用用户输入作为数值积分算法的函数?
【发布时间】: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 = 1x2 = 2.5exp((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


【解决方案1】:

正如@Tarik 评论的那样,首先检查您的代码逻辑。

然后试试eval(),例如:

from math import exp,sin


def integration(func_string, x1, x2):
    reverse = 0
    if x1 > x2:
        print('The calculated area will be negative')
        reverse = 1
        x1, x2 = x2, x1

    delta_x = (x2 - x1) / 1000
    # initialize
    A = 0.0
    x = x1

    while x <= x2:
        delta_A = eval(func_string) * delta_x
        x = x + delta_x
        A = A + delta_A
    if reverse == 1:
        A = -A
    print('Area under the curve', A)


if __name__=='__main__':
    x1 = float(input('x1='))
    x2 = float(input('x2='))
    integration('exp((x** 2)-x) * sin(x**3)', x1, x2)

示例 I/O:

x1=1
x2=2.5
Area under the curve 2.395500858985482

【讨论】:

  • 非常感谢您的宝贵时间。我会选择 Tarik 建议的 SciPy。我不知道 SciPy 的东西,它对微积分、工程和科学非常有用。我会坚持使用它的文档,我相信它会很有帮助。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2014-06-16
  • 2021-04-09
  • 1970-01-01
相关资源
最近更新 更多