如何在下限和上限之间数字地整合f(x)?

时间:2016-03-31 11:20:01

标签: python integral

我被告知要修改之前的代码,以便在下界a和上界b之间进行整合。这是通过添加另一个参数width来完成的。然后可以通过将大量具有面积(宽度* f(x))的矩形相加来计算积分。我需要计算的一个例子如下所示

  

计算f(x)= x的积分,从0到100。

我需要修改的代码是,这用于计算产品,如何修改它来计算积分?

def product(f, a, b):
    total = 1
    for i in range(a, b+1):
        total *= f(i)
    return total

2 个答案:

答案 0 :(得分:1)

<强>编辑:

假设您的函数f(x)计算x处的函数值,您可以执行以下操作:

def f(x): # define this according to your function.
    return x*x

def integrate(func, a, b, width):
    total = 0
    i = a
    while i <= b:
        total += func(i)
        i += width
    return total * width

width = 0.01
integral = integrate(f, 0, 100, width)
print(integral)

输出:

333283.3350000302

积分的真值是333333.333333,因此结果非常准确。

修改

要使用其他功能,例如sincos,您可以在函数f(x)内使用内置函数,如下所示:

def f(x):
    return math.sin(x)

然后从0到pi进行整合,使用:

width = 0.01
integral = integrate(f, 0, math.pi, width)
print(integral)

请记住使用import math导入数学。

答案 1 :(得分:1)

如果您的width需要为0.001,那么您必须使用除range以外的其他内容,因为它无法处理浮动值。

尝试while循环:

def integral(f, a, b, width):
    total = 0
    i = a
    while i <= b:
        total += f(i)
        i += width
    return total*width

编辑: 您可以像这样使用它:

def foo(x):
    return x
a = 0
b = 1
width = 0.001

integrated = integrate(foo, a, b, width)
print(integrated)

请注意,您不必将abwidth声明为变量;你可以直接传递它们。