MATLAB数值积分:基于牛顿-柯茨公式的定步长和自适应积分方法

时间:2025-03-09 08:40:26
  • function [ integration ] = CompoInt( func, left, right, step, mode )
  • % 分段积分牛顿-柯茨公式;
  • % 输入5个参数:被积函数(FUNCTIONHANDLE)'func',积分上下界'left'/'right',步长'step'
  • % 模式mode共三种('midpoint','trapezoid','simpson');
  • % 返回积分值;
  • switch mode
  • % 仅仅是公式不同
  • case 'midpoint'
  • node = left; integration = 0;
  • while (node + step <= right) % 按照给定步长开始分段积分
  • pieceInt = step*(func(node + step/2)); % 使用中点积分公式
  • integration = integration + pieceInt; node = node + step;
  • end
  • if (node < right) % 补齐最后一段积分
  • pieceInt = (right - node)*(func((node + right)/2));
  • integration = integration + pieceInt;
  • end
  • case 'trapezoid'
  • node = left; integration = 0;
  • while (node + step <= right)
  • pieceInt = step*(func(node) + func(node + step))/2; % 使用梯形公式
  • integration = integration + pieceInt; node = node + step;
  • end
  • if (node < right)
  • pieceInt = (right - node)*(func(node) + func(right))/2;
  • integration = integration + pieceInt;
  • end
  • case 'simpson'
  • node = left; integration = 0;
  • while (node + step <= right)
  • pieceInt = step*(func(node) + 4*func(node + step/2) + func(node + step))/6; % 使用辛普森公式
  • integration = integration + pieceInt; node = node + step;
  • end
  • if (node < right)
  • pieceInt = (right - node)*(func(node) + 4*func((node + right)/2) + func(right))/6;
  • integration = integration + pieceInt;
  • end
  • end