二重积分的复化Simpson方法

一般数值计算教材都只讲一重积分,很少讲二重积分和三重积分,这里我写了一个用Simpson方法求解二重积分的程序,供大家参考。程序的要点在于构建一个系数矩阵,具体教程可以参考
https://max.book118.com/html/2018/0419/162077258.shtm(张正印,二重积分的Simpson公式及其误差估计)


import math
import numpy as np  
import matplotlib.pyplot as plt
import sys
# this code calculate the 2d intergration with simpson method, the coffecient matrix is fixed and being created first, then the results can easily be calculated. . 

def grid_line1(n):# n is the size of x, should be odd
    grid=np.zeros(n,dtype=float)
    for i in range (0,n):
        if i%2==0:
            grid[i]=2
        else:
            grid[i]=4
    grid[0]=grid[-1]=1
    return grid
def grid_line2(n):# n is the size of x, should be odd
    grid=np.zeros(n,dtype=float)
    for i in range (0,n):
        if i%2==0:
            grid[i]=8
        else:
            grid[i]=16
    grid[0]=grid[-1]=4
    return grid
def grid_line3(n):# n is the size of x, should be odd
    grid=np.zeros(n,dtype=float)
    for i in range (0,n):
        if i%2==0:
            grid[i]=4
        else:
            grid[i]=8
    grid[0]=grid[-1]=2
    return grid
def simpson2d_grid(x,y):
    n=x.size
    m=y.size
    if n%2==0 or m%2==0:
        print("error, the size of x should be odd")
        sys.exit()
    else:
        grid1=grid_line1(n)
        grid2=grid_line2(n)
        grid3=grid_line3(n)
        grid0 = np.zeros((m,n),dtype=float)

        for i in range (0,m):
            if  i%2==0:
                grid0[i,:]=np.copy(grid3)

            else:
                grid0[i,:]=np.copy(grid2)
        grid0[0,:]=np.copy(grid1)
        grid0[-1,:]=np.copy(grid1)

    return grid0
def b(x0,y0):# the function is intergrate2d(ln(x+2*y)dxdy),x(1.4-2.0),y(1.0-1.5)

    return math.log(x0+2*y0)

xs = 1.4
xe = 2.0
ys = 1.0
ye = 1.5
n_x_grid=9
n_y_grid=9

x=np.linspace(xs,xe,n_x_grid)
y=np.linspace(ys,ye,n_y_grid)

coef_matrix=simpson2d_grid(x,y)
print(coef_matrix)
h=x[1]-x[0]
k=y[1]-y[0]
result = 0

for j in range(0,y.size):
    for i in range(x.size):
        result=result+h*k/9*coef_matrix[j,i]*b(x[i],y[j])
print(result)

系数矩阵和结果如下
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值