通过梯形规则集成函数-Python [英] Integrate a function by the trapezoidal rule- Python

查看:56
本文介绍了通过梯形规则集成函数-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要解决的作业:

最后一个问题的近似积分方法的进一步改进是将f(x)曲线下的区域划分为n个等距的梯形.

A further improvement of the approximate integration method from the last question is to divide the area under the f(x) curve into n equally-spaced trapezoids.

基于此思想,可以得出以下公式来近似积分:

Based on this idea, the following formula can be derived for approximating the integral:

!( https://www.dropbox.com/s/q84mx8r5ml1q7n1/Screenshot%202017-10-01%2016.09.32.png?dl = 0 )!

其中h是梯形的宽度, h =(ba)/n ,而 xi = a + ih,i∈0,...,n ,是梯形边的坐标.上图显示了梯形法则的概念.

where h is the width of the trapezoids, h=(b−a)/n, and xi=a+ih,i∈0,...,n, are the coordinates of the sides of the trapezoids. The figure above visualizes the idea of the trapezoidal rule.

在Python函数 trapezint(f,a,b,n)中实现此公式.您可能需要检查b是否>a,否则您可能需要交换变量.

Implement this formula in a Python function trapezint( f,a,b,n ). You may need to check and see if b > a, otherwise you may need to swap the variables.

例如, trapezint(math.sin,0,0.5 * math.pi,10)的结果应为0.9979(存在一些数字错误). trapezint(abs,-1,1,10)的结果应为2.0

For instance, the result of trapezint( math.sin,0,0.5*math.pi,10 ) should be 0.9979 (with some numerical error). The result of trapezint( abs,-1,1,10 ) should be 2.0

这是我的代码,但似乎未返回正确的值.
对于 print((trapezint(math.sin,0,0.5 * math.pi,10)))
我应该得到 0.9979
时得到0.012286334153465965对于 print(trapezint(abs,-1,1,10))
我应该得到 1.0 时得到0.18000000000000002.

This is my code but It doesn't seem to return the right values.
For print ((trapezint( math.sin,0,0.5*math.pi,10)))
I get 0.012286334153465965, when I am suppose to get 0.9979
For print (trapezint(abs, -1, 1, 10))
I get 0.18000000000000002, when I am suppose to get 1.0.

import math
def trapezint(f,a,b,n):

    g = 0
    if b>a:
        h = (b-a)/float(n)
        for i in range (0,n):
            k = 0.5*h*(f(a+i*h) + f(a + (i+1)*h))
            g = g + k
            return g
    else:
        a,b=b,a
        h = (b-a)/float(n)
        for i in range(0,n):
            k = 0.5*h*(f(a + i*h) + f(a + (i + 1)*h))
            g = g + k
            return g

print ((trapezint( math.sin,0,0.5*math.pi,10)))
print (trapezint(abs, -1, 1, 10))

推荐答案

此变体降低了分支的复杂性并减少了操作数.最后一步的求和被简化为对数组的单个操作.

This variation reduces the complexity of branches and reduces number of operations. The summation in last step is reduced to single operation on an array.

from math import pi, sin
def trapezoid(f, a, b, n):
    if b < a:
        a,b = b, a
    h = (b - a)/float(n)
    g = [(0.5 * h * (f(a + (i * h)) + f(a  + ((i + 1) * h)))) for i in range(0, n)]
    return sum(g)

assert trapezoid(sin, 0, 0.5*pi, 10) == 0.9979429863543573
assert trapezoid(abs, -1, 1, 10) == 1.0000000000000002

这篇关于通过梯形规则集成函数-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆