Using Simpson's rule to integrate function

조회 수: 36 (최근 30일)
Ryan Bowman
Ryan Bowman 2018년 11월 13일
다시 열림: Walter Roberson 2018년 12월 20일
I have a function in which I'm trying to solve by integrating. I must use Simpson's rule with for loops to solve. This is what I have so far but I'm unsure how to tailor this better to what I need: I'm trying to integrate the "mass flow" function.
syms p T R A time
rho = 1.225; %kg/m^3
T = 288.15; %Kelvin
R = 287.057; %m^2/s^2*K
A = 0.01; %area of wind tunnel
gamma = 1.4;
M = 2.4; %Mach # that V0 is running at
a = sqrt(gamma*R*T);%speed of sound of air
V0 = M*a; %speed of V0
VF = 0.00001; %m/s
VelocityFunction = 0.00001 == 816.71*exp(-10*time);
TotalTime = solve(VelocityFunction, time);
TotalTime = double(TotalTime);
massflow = @(t) rho*A*V0*exp(-10*t);
delX = 0.01;
XVals = 0:delX:1;
fvals = f(XVals);
resultTrap = 0;
for idx = 1:length(XVals)-1
resultTrap = resultTrap + (fvals(idx) + fvals(idx + 1))/2*delX;
end
myResult = resultTrap
xVals = 0;
for idx = 1:10 %first value will be zero
xVals(idx+1) = xVals(idx) + rand(1);
end
xVals = xVals/(max(xVals)) %normalizing output here
fVals = f(xVals);
resultTrapRand = 0;
for idx = 1:length(xVals)-1
resultTrapRand = resultTrapRand + (fVals(idx) + fVals(idx +1))/2*(xVals(idx+1) - xVals(idx));
end
myResultRand = resultTrapRand
  댓글 수: 2
Jim Riggs
Jim Riggs 2018년 11월 13일
I am rather confused by your code.
What function are you wanting to integrate?
You have defined a function "massflow", but this function is never referenced.
It looks like you are referencing some function "f" (as in f(XVals)) but f is not defined.
Ryan Bowman
Ryan Bowman 2018년 11월 14일
This is actually I mistake I have made. I am wanting to integrate the "massflow" function.

댓글을 달려면 로그인하십시오.

채택된 답변

Jim Riggs
Jim Riggs 2018년 11월 14일
편집: Jim Riggs 2018년 11월 14일
OK. now I understand.
I prefer to code an integration loop as follows;
For the trapezoidal solution:
StartTime = 0;
EndTime = 1.0;
Tstep = 0.001;
Tsum = 0;
for time = StartTime+Tstep:Tstep:EndTime
Tsum = Tsum + Tstep/2*(massflow(time-Tstep) + massflow(time));
end
Tsum is the Trapezoidal integration solution.
For the Simpson's rule solution:
Sstep = 0.02;
Ssum = 0;
for time = StartTime+2*Sstep:2*Sstep:EndTime
Ssum = Ssum + Sstep/3*(massflow(time-2*Sstep) + 4*massflow(time-Sstep) + massflow(time));
end
Ssum is the Simpson's rule integration solution.
Using the above, you can set a different step size for the trapezoidal method and Simpson's method.
You will see that the Trapezoidal rule solution requires a step that is several orders of magnitude smaller than Simpson's rule for similar accuracy.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by