Anonymous user
Numerical integration: Difference between revisions
→{{header|MATLAB}}: Changed the solution to conform with the task specs and added a more detailed example of how to use the solution functions
(→{{header|MATLAB}}: Changed the solution to conform with the task specs and added a more detailed example of how to use the solution functions) |
|||
Line 1,102:
=={{header|MATLAB}}==
For all of the examples given, the function that is passed to the method as parameter f is a function handle.
</lang>▼
Function for performing left rectangular integration: leftRectIntegration.m
<lang MATLAB>function integral = leftRectIntegration(f,a,b,n)
format long;▼
x1=linspace(a,b,n+1); ▼
▲ format long;
x2=linspace(a,b,n+1); ▼
width = (b-a)/n; %calculate the width of each devision
integral = width * sum( f(x(1:n-1)) );
▲end</lang>
Function for performing right rectangular integration: rightRectIntegration.m
x3=linspace(a,b,n+1);▼
<lang MATLAB>function integral = rightRectIntegration(f,a,b,n)
MdPtRl=h.*sum(f((x3(1:n)+x3(2:n+1))/2))▼
format long;
x4=linspace(a,b,n+1); ▼
width = (b-a)/n; %calculate the width of each devision
integral = width * sum( f(x(2:n)) );
end</lang>▼
Function for performing mid-point rectangular integration: midPointRectIntegration.m
<lang MATLAB>function integral = midPointRectIntegration(f,a,b,n)
▲</lang>
format long;
width = (b-a)/n; %calculate the width of each devision
end</lang>
Function for performing trapezoidal integration: trapezoidalIntegration.m
<lang MATLAB>function integral = trapezoidalIntegration(f,a,b,n)
format long;
integral = trapz( x,f(x) );
end</lang>
Simpson's rule for numerical integration is already included in MATLAB as "quad()". It is not the same as the above examples, instead of specifying the amount of points to divide the x-axis into, the programmer passes the acceptable error tolerance for the calculation (parameter "tol").
<lang MATLAB>integral = quad(f,a,b,tol)</lang>
{{header|Sample inputs}}
Using anonymous functions
<lang MATLAB>trapezoidalIntegration(@(x)( exp(-(x.^2)) ),0,10,100000)
ans =
0.886226925452753</lang>
Using predefined functions
Built-in MATLAB function sin(x):
<lang MATLAB>quad(@sin,0,pi,1/1000000000000)
ans =
2.000000000000000</lang>
User defined scripts and functions:
fermiDirac.m
<lang MATLAB>function answer = fermiDirac(x)
k = 8.617343e-5; %Boltazmann's Constant in eV/K
answer = 1./( 1+exp( (x)/(k*2000) ) ); %Fermi-Dirac distribution with mu = 0 and T = 2000K
end</lang>
<lang MATLAB> rightRectIntegration(@fermiDirac,-1,1,1000000)
ans =
0.999998006023282</lang>
=={{header|OCaml}}==
|