Using Simpson's rule to integrate function

3 visualizzazioni (ultimi 30 giorni)
Ryan Bowman
Ryan Bowman il 13 Nov 2018
Riaperto: Walter Roberson il 20 Dic 2018
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 Commenti
Jim Riggs
Jim Riggs il 13 Nov 2018
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 il 14 Nov 2018
This is actually I mistake I have made. I am wanting to integrate the "massflow" function.

Accedi per commentare.

Risposta accettata

Jim Riggs
Jim Riggs il 14 Nov 2018
Modificato: Jim Riggs il 14 Nov 2018
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.

Più risposte (0)

Prodotti


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by