/
Integrals.m
55 lines (44 loc) · 1.46 KB
/
Integrals.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
%% Definite and indefinite integrals
% Nick Trefethen, October 2012
%%
% (Chebfun example calc/Integrals.m)
% [Tags: #integral, #SUM, #CUMSUM]
%%
% Suppose we have a function, like this one:
x = chebfun('x',[0 10]);
f = round(2*cos(x));
plot(f), ylim(2.5*[-1 1])
%%
% The Chebfun command `sum` returns the definite integral over the prescribed
% interval, which is just a number:
format long, sum(f)
%%
% You can also calculate the definite interval over a subinterval by giving
% two additional arguments, like this:
sum(f,3,4)
%%
% To compute an indefinite integral, use the Chebfun command `cumsum`.
% This returns a chebfun defined over the given interval:
g = cumsum(f);
plot(g,'m')
%%
% Thus another way to compute the integral over a subinterval would be to take
% the difference of two values of the cumsum:
g(4) - g(3)
%%
% As always in calculus, when working with indefinite integrals you must be
% careful to remember the arbitrary constant that may be added. Thus for
% example, if you integrate $f$ and then differentiate it, you get $f$ back
% again:
norm( diff(cumsum(f)) - f )
%%
% If you differentiate $f$ and then integrate it, on the other hand, you get
% something different:
norm( cumsum(diff(f)) - f )
%%
% Plotting the two instantly alerts us that we forgot to add back in the value
% at the left endpoint, namely $f(0) = 2$:
plot(f,'b',cumsum(diff(f)),'r')
%%
% Sure enough, adding this number makes the two functions agree:
norm( f(0)+cumsum(diff(f)) - f)