Using Simpson's rule to integrate function
3 次查看(过去 30 天)
显示 更早的评论
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
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.
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!