Here is the summary of the integral calculation that we did in class
today:
To calculate the integral of a function exp(-x^2) from 0 to L, we found
the Taylor series for this function (sum for n from 0 to infinity of
(-1)^n x^(2n) / n! ), and integrated it term by term from 0 to L, which
yields a sum for n from 0 to infinity of (-1)^n L^(2n+1) / (2n+1) / n!
To calculate the result with "m" number of terms in the series, create
the following m-file (call it "MyIntegral.m", for instance)
function I = MyIntegral(m)
I = 0; L = 1;
fprintf(' Order: Integral value:\n');
for n = 0 : m
an = (-1)^n * L^(2*n+1) / (2*n+1) / factorial(n);
I = I + an;
fprintf(' m = %2d I = %9.6g \n', n, I)
end
Now when you enter a command "MyIntegral(7)", you will see the result
approach the true value of the integral (which is equal to
0.746824133), as the number of terms in the Taylor polynomial
approximation is increased from 0 to 7.
Please make sure you understand exactly what each line in this program
does, and let me know if you have any questions. We will eventually
move to more complicated programs, so you should feel comfortable with
short programs like this one, involving a "for" cycle.
Note that you can make the upper limit of integration L to serve as the
2nd argument of your function "MyIntegral", instead of fixing the value
of L in the body of the m-file. This will make this function more
useful (more flexible). To do this, simply replace the first command
with "function I = MyIntegral(m,L)"