Answers to excercises

Answers to excercises
January 27, 2009
2
Chapter 1
Answers Chapter 1
Exercises
1.1
a) Trapezoid rule:
Z
1
0
3
1
1
1
1
= .
dx ≈ (1 − 0)
+
1+x
2 1+0 1+1
4
b) Exact solution:
Z
0
relative error:
1
1
dx = [ln(1 + x)]10 = ln 2 = 0.6931,
1+x
| ln 2 − 34 |
= 0.08292 (≈ 8.2%).
| ln 2|
c) Composite Trapezoid (n=2):
Z
0
relative error:
1
1
17
1 1 1
1
1 1
=
dx ≈
+
+
,
1+x
2 2 1 + 0 1 + 0.5 2 1 + 1
24
17
|
| ln 2 − 24
= 0.02191 (≈ 2.2%).
| ln 2|
d) Composite Trapezoid (n=3):
Z
0
1
1
1 1 1
1
dx ≈
+
1+x
3 21+0 1+
relative error:
1
3
1
+
1+
2
3
7
1 1
=
,
+
21+1
10
7
| ln 2 − 10
|
= 0.00989 (≈ 1%).
| ln 2|
3
CHAPTER 1. ANSWERS CHAPTER 1
4
e) Observe that the error (Eh ) divided by h2 seems to converge to (approximately)
1
:
0.0625. We want the relative error (Eh / ln 2) to be less than 1000
0.0625h2
ln 2
1
n2
n
1
1000
ln 2
<
62.5
≥ 10
<
(n must be an integer.)
1.2
a) Exact values:
Z
1
2
0
Z
0
1
sin xdx = [− cos x]02 = 0.12242
1
2
12
1
sin(5x)dx = − cos(5x) = 0.36023
5
0
b) Composite Trapezoid (n=2):
Z
1
2
0
relative error:
Z
1
2
0
relative error:
sin xdx ≈
1 1
1 1
1
= 0.12178,
sin 0 + sin + sin
4 2
4 2
2
|0.12242 − 0.12178|
= 0.00523(≈ 0.5%).
|0.12242|
1 1
5 1
5
= 0.31206,
sin(5x)dx ≈
sin 0 + sin + sin
4 2
4 2
2
|0.36023 − 0.31206|
= 0.13372 (≈ 13%).
|0.36023|
c) See figure 1.1. This figure was produced by the program ex12 c.m. To see why the
error is larger, take second derivatives of the two functions.
1.3
a) Easy
b) Easy (exact results if n is an even number).
c) Easy
d) Problematic: f (x) is infinite at x = 0. This means that the area of one of the
trapezoids will also be infinite.
5
1
f(x)
g(x)
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
Figure 1.1: Exercise 1.2. For f (x) the function and the trapezoids are almost indistinguishable, indicating that the error of the approximatization is low. For g(x) the
difference is more significant.
1.4 c)
See the program trapezoidal.m. Using this program on the examples in exercise 1.3
we find that:
a) E/h2 = 1.0
0
b) E/h2 =
0.25
n is an even number
n is an odd number
c) E/h2 = 0, note the symmetry of the function.
d) The program does not work for this problem, see 1.3 d.
Projects
1.7
a) Using the definition of the error we find that
Z
Z
Z
Z b
b
b
b
f (x) − y(x) dx .
y(x) dx = f (x) dx −
f (x) dx − T (f, a, b) = E=
a
a
a
a
b) Using an integral inequality it follows that
Z
Z
b
b
|f (x) − y(x)| dx.
f (x) − y(x) dx ≤
E=
a
a
CHAPTER 1. ANSWERS CHAPTER 1
6
c) From equations (1.34) and (1.35):
E≤
Z
a
b
|f (x) − y(x)| dx ≤ (b − a) max |−y(x)| .
a≤x≤b
d) Taylor’s Theorem inply that:
f (x) = f (a) + f ′ (a)(x − a) + f ′′ (ξ)
(x − a)2
.
2
Trapezoid:
y(x) = f (a) +
f (b) − f (a)
(x − a).
b−a
That is
f (b) − f (a)
(x − a)2
− f (a) +
(x − a)
f (x) − y(x) = f (a) + f ′ (a)(x − a) + f ′′ (ξ)
2
b−a
1
f (b) − f (a)
(x − a) + (x − a)2 f ′′ (ξ).
=
f ′ (a) −
b−a
2
e) Taylor’s Theorem:
f (b) = f (a) + f ′ (a)(b − a) + f ′′ (η)
(b − a)2
,
2
f (b) − f (a)
1
= f ′ (a) + (b − a)f ′′ (η).
b−a
2
Apply this to the result from part 4.
f) An upper limit for |f (x) − y(x)|:
= − 12 (x − a)(b − a)f ′′ (η) + 21 (x − a)2 f ′′ (ξ)
≤ − 21 (x − a)(b − a)f ′′ (η) + 21 (x − a)2 f ′′ (ξ)
≤ − 12 (b − a)2 f ′′ (η) + 21 (b − a)2 f ′′ (ξ)
≤ − 12 (b − a)2 M + 21 (b − a)2 M |f (x) − y(x)|
= M (b − a)2 .
from part 5
triangle inequality
because (b − a) ≥ (x − a)
M ≥ f ′′ (η), M ≥ f ′′ (ξ)
g) And thus an upper limit for the error is given by:
E≤
Z
a
b
|f (x) − y(x)| dx ≤
Z
a
b
M (b − a)2 dx = M (b − a)3 .
7
h) The composite trapezoid rule:
"
#
n−1
X
1
1
= h f (x0 ) +
f (xi ) + f (xn )
2
2
i=1
#
"
n−1
X
h
f (xi ) + f (xn )
f (x0 ) + 2
=
2
i=1
" n
#
h X
(f (xi−1 + f (xi ))
=
2 i=1
Tn
n
X
h
=
i=1
n
X
=
2
(f (xi−1 + f (xi ))
T (f, xi−1 , xi )
i=1
i) Using the triangle inequality on the definition of En :
n Z
Z
X xi
b
f (x) dx − T (f, xi−1 , xi )
f (x) dx − Tn = En = a
x
i−1
i=1
Z i
n x
X
f (x) dx − T (f, xi−1 , xi ) .
≤
xi−1
i=1
j) Using the results from 1.7.7 and 1.7.9 on each interval we find that:
n
X
En ≤
i=1
Mi (xi − xi−1 )3 ≤ M
n
X
i=1
(xi − xi−1 )3 .
k) Remember that nh = b − a:
En ≤ M
n
X
i=1
(xi − xi−1 )3 = M
n
X
i=1
h3 = M nh3 = M (b − a)h2 .
l) Comparing (1.33) with the results from 1.4:
a) En /h2 ≤ 1/2. Consistent with the result obtained in 1.4 a).
b) |x| is not differentiable at x = 0, inequality (1.33) can not be used.
c) En /h2 ≤ π 2 /6. Consistent with the result obtained in 1.4 c).
1.8
a) Midpoint rule:
Z
a
b
p0 (x)dx =
Z
a
b
f(
a−b
a−b
)dx = f (
)
2
2
Z
b
a
dx = (b − a)f (
a−b
).
2
CHAPTER 1. ANSWERS CHAPTER 1
8
b) Midpoint rule applied to (1.45):
(b − a)f (
relative error:
1
8
a−b
) = f( ) =
,
2
2
225
8
1
− 225
|
| 24
11
=
(≈ 15%).
1
75
| 24 |
c) Composite midpoint rule:
Z
b
f (x)dx =
a
n−1
X Z xi+1
xi
i=0
f (x)dx ≈
n−1
X
i=0
(xi+1 −xi )f (
n−1
X
xi+1 + xi
f (xi+1/2 ).
)=h
2
i=0
Composite midpoint rule applied to (1.45), using n=2:
Z
b
f (x)dx ≈
a
Relative error:
1
2
1
3
f ( ) + f ( ) = 0.03980.
4
4
1
− 0.03980|
| 24
= 0.04480 (≈ 5%).
1
| 24
|
d) See the program midp.m, E ≈ 0.008h2 .
e) Trapezoid rule:
Z
1
0
1
1
f (x)dx ≈ (1 − 0) (f (0) + f (1)) =
,
2
18
relative error:
1
1
− 18
|
| 24
1
= (≈ 33%).
1
3
| 24 |
f) Simpson’s rule:
Z
0
1
f (x)dx ≈
relative error:
(1 − 0)
1
19
[f (0) + 4f ( ) + f (1)] =
,
6
2
450
19
1
− 450
|
| 24
1
(≈ 1.3%)
=
1
75
| 24 |
g) Composite Simpson’s rule:
Z
a
b
f (x)dx =
n Z
X
i=1
xi
xi−1
f (x)dx ≈
n
X
xi+1 − xi
i=1
h) See the program simprule.m, E ≈ 0.001h4 .
6
[f (xi−1 )+4f (xi−1/2 )+f (xi )].
9
1.9
a) The theorem of Pythagoras applied to the triangle in figure (1.11) yields:
s2 = (∆x)2 + (∆y)2 = (∆x)2 + (y(x + ∆x) − y(x))2 .
b) Taylor: y(x + ∆x) ≈ y(x) + ∆xy ′ (x),
(∆x)2 + (y(x + ∆x) − y(x))2 ≈ (∆x)2 + (∆x)2 (y ′ (x))2 .
c) In each interval: Use the distance between the endpoints as an approximation of the
lenght of the graph.
l(y, a, b) =
n
X
i=1
si ≈
n
X
i=1
p
∆x 1 + (y ′ (xi ))2
d) This is a Riemann sum. When ∆x → 0 it converges towards an integral.
lim
∆x→0
X
i
∆xi
Z
p
1 + (y ′ (xi ))2 =
a
b
p
1 + (y ′ (xi ))2 dx.
e) + F) 1/8 of a circle (unit circle: x2 + y 2 = 1):
y(x) =
Z
0
√
2
2
p
p
−x
,
1 − x2
Z √22 r
1 − x2 , y ′ (x) = √
1 + (y ′ (x))2 dx =
0
√
2
π
1
dx = [arcsin x]02 = .
2
1−x
4
g) Run in MATLAB:
for n=10:10:100
(trapezoidal(0,sqrt(2)/2,’1/sqrt(1-x*x)’,n)-pi/4)*2*nˆ2
end
R 250 p
h) Each patch of cable: L = 0
1 + (y ′ (x))2 dx, y ′ (x) = 0.006x.
i) Run in MATLAB:
4*trapezoidal(0,250,’sqrt(1+(0.006*x)ˆ2)’,20)
ans =
1.2999e+03
Programs (MATLAB)
ex2 c.m
% Script for making a figure of two functions
% and trapezoides with n=2.
% example: >>ex2_c
CHAPTER 1. ANSWERS CHAPTER 1
10
x=0:0.01:0.5;
xt=0:0.25:0.5;
f=sin(x);
g=sin(5*x);
gt=sin(5*xt);
ft=sin(xt);
plot(x,f,x,g,’r--’);legend(’f(x)’,’g(x)’);
hold on;
plot(xt,ft,xt,gt,’r--’);
stem(xt,ft);stem(xt,gt,’r--’);
hold off;
trapezoidal.m
function r = trapeziodal(a,b,f,n)
% Use the composite trapezoidal method, with n trapezoids,
% to compute the integral of the function f from a to b.
% example: trapezoidal(0,1,’xˆ4’,12) .
f= fcnchk(f);
h=(b-a)/n;
s=0;
x=a;
for i = 1:n-1
x=x+h;
s=s + feval(f,x);
end
s= 0.5*(feval(f,a) +feval(f,b)) +s;
r = h*s;
midp.m
function r = midp(a,b,f,n)
% Use the composite midpoint metod, with n points,
% to compute the integral of the function f from a to b.
% example: midp(0,1,’x./(4-x.*x).ˆ2’,8)
f= fcnchk(f);
h=(b-a)/n;
x=(a+h*0.5):h:(b-h*0.5);
y=feval(f,x);
r= h*sum(y(1:n));
11
simprule.m
function r = simprule(a,b, f, n)
% Use the composite Simpson’s rule, with n intervals,
% to compute the integral of the function f from a to b.
% example: simprule(0,1,’x./(4-x.*x).ˆ2’,8)
f= fcnchk(f);
h=(b-a)/n;
s=0; x=a;
for i = 1:n-1
x=x+h;
s=s + 2*feval(f,x) +4*feval(f,x-h/2);
end
s= (feval(f,a) +feval(f,b) +4*feval(f,b-h/2) ) +s;
r = h*s/6;
12
CHAPTER 1. ANSWERS CHAPTER 1
Chapter 2
Answers Chapter 2
Exercises
2.1
a) r′ (t) = e4t = 1 + 4r(t), r(0) = 14 (e0 − 1) = 0
b) Use the approximation y ′ (tn ) ≈
y(tn+1 )−y(tn )
:
∆t
yn+1 − yn
= 1 + 4yn ⇒ yn+1 = yn + ∆t(1 + 4yn )
∆t
c) Use the approximation z ′ (tn+1 ) ≈
z(tn+1 )−z(tn )
:
∆t
zn+1 − zn
zn + ∆t
= 1 + 4zn+1 ⇒ zn+1 =
∆t
1 − 4∆t
y1 =
d)
y2 =
y3 =
1
10
24
100
109
250
1
6
z2 = 94
49
z3 = 54
z1 =
r(∆t) = 0.12
r(2∆t) = 0.30
r(3∆t) = 0.58
e) See the program ex21.m.
f) E/∆t ≈ 109.
2.2
a) r′ (t) = et + 2t = r(t) + 2t − t2 , r(0) = e0 + 02 = 1
b) Use the approximation y ′ (tn ) ≈
y(tn+1 )−y(tn )
:
∆t
yn+1 − yn
= yn + 2tn − t2n ⇒ yn+1 = yn + ∆t(yn − 2tn − t2n )
∆t
13
CHAPTER 2. ANSWERS CHAPTER 2
14
c) Use the approximation z ′ (tn+1 ) ≈
z(tn+1 )−z(tn )
:
∆t
zn + ∆t(2tn+1 − t2n+1 )
zn+1 − zn
= yn+1 + 2tn+1 − t2n+1 ⇒ zn+1 =
∆t
1 + ∆t
y1 = 1.1
y2 = 1.229
y3 = 1.388
d)
z1 = 1.132
z2 = 1.298
z3 = 1.499
r(∆t) = 1.115
r(2∆t) = 1.269
r(3∆t) = 1.440
e) See the program ex22.m.
f) E/∆t ≈ 3.1
2.3
a) r(1) = r0 e50·1 (= 5.18 · 1024 )
b) An upper estimate is 1100e50 (= 5.70 · 1024 ).
A lower estimate is 900e50 (= 4.67 · 1024 ).
c) An upper estimate is 1100e60 (= 1.26 · 1029 ).
A lower estimate is 900e40 (= 2.12 · 1020 ).
2.4
a) r(1) = 8790 (= R)
b) An upper and lower estimate is 8790.
c) An upper and lower estimate is 8790.
d) An upper estimate is 10000, and a lower estimate is 7000.
2.5
a) a = 0.03, r0 = 5.3, t =years since 1800; r(t) = 5.3e0.03t .
b) When defining t as the year the formula becomes r(t) = 5.3e0.03(t−1800) .
c) See the program ex25.m.
d) r(1980) = 1173.
e) See the program ex25.m. 290 is a good value for R. (Try it!) This gives the result
r(1980) = 233.4.
15
2.6
a) Note that
rn = 1 ⇒ rn+1 =
p
1 −1 + ∆t + 1 + 2∆t + (∆t)2 = 1.
2∆t
If rn is 1 then rn+1 = 1. By a simple induction argument we find that if r0 = 1
then rn = 1 for all n ≥ 0. Next, observe that
p
1 −1 + ∆t + (1 − ∆t)2 = 0.
2∆t
rn = 0 ⇒ rn+1 =
If rn is 0 then rn+1 = 0. By a simple induction argument we find that if r0 = 0
then rn = 0 for all n ≥ 0.
b) f (1) = 1 − rn . We know that (1 − rn ) > 0 since rn < 1.
f (rn ) = −∆trn (1 − rn ), this must be negative, since we know that rn , (rn − 1),
and ∆t, are all positive.
c) f (0) = −rn , we know that rn > 0:
f (−∞) = lim (1 − ∆t)r + ∆tr2 − rn > 0
r→−∞
e) For rn > 1:
f (rn ) = −∆trn (1 − rn ) > 0,
f (1) = 1 − rn < 0
2.7
a)
u(tn+1 ) =
Z
tn+1
u′ (t) dt =
c) Midpoint rule: Replace
d) Simpson’s rule: Replace
in (2.58).
R tn+1
R tn+1
tn
a) y(t) = et
b) y(t) =
α
1−tα
c) y(t) = ln( 12 t2 + e)
tn+1
tn
Z
u′ (t) dt = u(tn )+
f (u(t)) dt with
tn+1
f (u(t)) dt
tn
∆t
2
(f (un+1 ) + f (un )) in (2.58).
f (u(t)) dt with ∆tf
R tn+1
tn
Z
u′ (t) dt+
f (u(t)) dt with
tn
e) See the program ex27.java.
2.8
tn
0
0
b) Trapezoid rule: Replace
Z
∆t
6
1
2 (un+1
+ un ) in (2.58).
f (un+1 ) + 4f
1
2 (un+1
+ un ) + f (un )
CHAPTER 2. ANSWERS CHAPTER 2
16
2
s
1.5
1
0.5
0
0
0.5
1
1.5
2
2.5
t
3
3.5
4
4.5
5
Figure 2.1: Solutions of s(t) for different values of x. Differences in x seems to have
little effect on the solution at high values of t, except for x = 0.
Projects
2.4.1
a) If s(t) = x/(x + e−t (1 − x)) then
s′ (t) =
xe−t (1 − x)
= s(1 − s),
(x + e−t (1 − x))2
and
s(0) =
x
= x.
x+1−x
b) See Figure 2.1.
c) +d) See Figure 2.2.
S ′ (x) =
x + e−1 (1 − x) − (1 − e−1 )x
1
=
−1
2
−1
(x + e (1 − x))
e(e x − x − e−1 )2
e) We have from the Taylor series that
S(x + ε) ≈ S(x) + εS ′ (x).
This means that small perturbations ε of the initial data will be more significant the
greater S ′ (x) is compared to S(x). We see from Figure 2.2 that S ′ (x) is small compared to S(x) exept at very low values of x. We conclude that small perturbations
of the initial data will only have a significant effect on the solution close to x = 0.
This is consistent with the results in Figure 2.1.
17
3
S(x)
S′(x)
2.5
2
1.5
1
0.5
0
0
0.5
1
1.5
Figure 2.2: S(x) =
2
2.5
x
x
x+e−1 (1−x)
3
3.5
and S ′ (x) =
4
4.5
5
1
e(e−1 x−x−e−1 )2
f) If u(t) = x/(x + et (1 − x)) then
u′ (t) =
−xet (1 − x)
= u(u − 1),
(x + et (1 − x))2
and
u(0) =
x
= x.
x+1−x
g) For (0 < x < 1) : limt→∞ u(t) = 0
1
For (x = 1) : u(t) = 1+0
= 1.
x
For (x > 1) : u t → ln x−1 = ∞
h) See Figure 2.3.
i) U (1) = 1, U (1.0000454) = 2.2805·104 . Close to x = 1 the expression is extremely
unstable with respect to small perturbations of x.
2.4.2
a) The Taylor series can be written as
u(t + k) =
3
X
u(n) (t) n u(4) (ξ) 4
k +
k .
n!
4!
n=0
The final term is the remainder term, and is often simlpy written as O(k 4 ).
CHAPTER 2. ANSWERS CHAPTER 2
18
3
2.5
2
t
1.5
1
0.5
0
−0.5
−1
0
0.5
1
1.5
2
2.5
u
3
3.5
4
4.5
5
Figure 2.3: Solutions of u(t) for different values of t. Differences in the initial value x
seems to have little effect on the solution at high values of t, except for x = 1.
b)
1 1
∆t
+
2 2
1
∆t ′
= u
n+
∆t +
n+
u
2
2
2 1 ∆t
1
′′
+
∆t +
n+
u
2 2
2
u(tn+1 ) = u
u(tn )
(n +
1 1
∆t
−
2 2
∆t ′
1
= u
n+
∆t −
n+
u
2
2
2 1 ∆t
1
′′
+
∆t −
n+
u
2 2
2
= u
1
2
∆t
1
6
∆t
∆t
2
3
1
∆t + O(∆t4 )
n+
u
2
′′′
(n +
1
2
1
6
∆t
2
3
u
′′′
1
n+
2
∆t + O(∆t4 )
c) Combining the two equations from exercise b gives
2
u(tn+1 )−u(tn ) = ∆tu (tn+ 12 )+
6
′
∆t
2
3
u
′′′
1
n+
2
∆t +On+1 (∆t4 )−On (∆t4 ).
We consider all but the first term to be the remainder, O(∆t3 ), and divide by ∆t on
both sides of the equation, leading to
19
u(tn+1 ) − u(tn )
= u′ (tn+ 12 ) + O(∆t2 ).
∆t
d) Equation (2.69) means we can replace u′ (tn+ 21 ) with f (u(tn+ 21 )) in the equation
obtained in exercise c.
e) We take the Taylor series of the functions f (u(tn )) and f (u(tn+1 )):
f (u(tn )) = f (u(tn+1/2 ))+(−
∆t ′
u (n+t1/2 )+O(∆t2 ))f ′ (u(tn+1/2 ))+O(∆t2 )
2
f (u(tn+1 )) = f (u(tn+1/2 ))+(
∆t ′
u (n+t1/2 )+O(∆t2 ))f ′ (u(tn+1/2 ))+O(∆t2 )
2
Combining the two equations gives
1
(f (u(tn )) + f (u(tn+1 ))) = f (u(tn+1/2 )) + O(∆t2 ).
2
Combining this with the result from exercise c, we find that
u(tn+1 ) − u(tn )
∆t
= u′ (tn+ 21 ) + O(∆t2 )
= f (u(tn+ 12 )) + O(∆t2 )
=
1
(f (u(tn )) + f (u(tn+1 ))) + O(∆t2 ).
2
f) Removing O(∆t2 ) from the equation in exercise e gives us the approximation un ≈
u(tn ):
un+1 − un
∆t
∆t
f (un+1 )
un+1 −
2
f (un+1 ) + f (un )
,
2
∆t
= un +
f (un )
2
=
g) See the program pro242.java. At time T = 5 the results are:
N
50
100
200
(error explicit Euler)/∆t
2.09
2.27
2.38
(error imlicit Euler)/∆t
3.07
2.76
2.62
(error Crank-Nicolson)/∆t2
0.42
0.42
0.42
h) See the program pro242h.java. At time T = 1 the results are:
N
20
40
80
(error explicit Euler)/∆t
1.89
1.81
1.79
(error imlicit Euler)/∆t
1.75
1.76
1.77
(error Crank-Nicolson)/∆t2
3.31
3.23
3.21
CHAPTER 2. ANSWERS CHAPTER 2
20
i) In general,
u(tn+1 ) − u(tn )
1
= (f (u(tn )) + f (u(tn+1 ))) + O(∆t2 ).
∆t
2
We can approximate f (u(tn+1 )) by f (un + ∆tf (un )). The error in this approximation is O(∆t2 ). This produces the formula
un+1 = un +
∆t
[f (un )) + f (un + ∆tf (un ))] .
2
This is known as the Heun scheme.
j) See the program pro242j.java.
(error Heun)/∆t2
0.77
0.80
0.82
N
50
Repeating the experiments in exercise g for T = 5:
100
200
N
20
Repeating the experiments in exercise h for T = 1:
40
80
(error Heun)/∆t2
2.59
2.46
2.33
k) The explicit Euler scheme can be derived from the Taylor series of u(tn + ∆t):
u(tn+1 ) = u(tn + ∆t) = u(tn ) + ∆tu′ (tn ) + O(∆t2 )
This leads to the approximation
un+1
= un + ∆tu′n
= un + f (tn , un ).
The implicit Euler scheme is derived in a similar fashion:
u(tn ) = u(tn+1 − ∆t) = u(tn+1 ) − ∆tu′ (tn+1 ) + O(∆t2 )
This leads to the approximation
un
= un+1 − ∆tu′n+1
= un+1 − ∆tf (tn+1 , un+1 ).
The Crank-Nicholson scheme is derived as in exercise f, replacing f (un ) with
f (tn , un ) and f (un+1 ) with f (tn+1 , un+1 ).
The Heun scheme is derived as in exercise i, replacing f (un ) with F1 = f (tn , un ),
and f (un + ∆tf (un )) with F2 = f (tn+1 , un + ∆tF1 ).
21
l) We adjust the program pro242j.java so that it uses the fourth order Runge-Kutta
scheme, giving the following results:
Repeating the experiments in exercise g for T = 5:
N
error/∆t
error/∆t2
error/∆t3
error/∆t4
−5
−4
−3
50 3.83 · 10
3.83 · 10
3.83 · 10
3.83 · 10−2
−6
−5
−3
100 5.00 · 10
9.91 · 10
2.00 · 10
4.00 · 10−2
−7
−5
−3
200 6.38 · 10
2.55 · 10
1.02 · 10
4.08 · 10−2
Repeating the experiments in exercise h for T = 1:
N
error/∆t
error/∆t2
error/∆t3
error/∆t4
−5
−3
40 8.33 · 10
3.33 · 10
0.133
5.33
80 1.15 · 10−5 9.19 · 10−4 7.36 · 10−2
5.88
160 1.46 · 10−6 2.34 · 10−4 3.75 · 10−2
6.00
m) If u(t) = e−(
1−t 2
ε )
error/∆t5
0.383
0.80
1.63
error/∆t5
213
471
959
then
u′ (t) = e−(
1−t 2
ε )
(
2
2t
2(1 − t)
− 2) = u
,
ε2
ε
ε2
and
u(0) = e−(
1−0 2
ε )
−1
= e ε2 .
n) The program pro242n.java can be used to compare the schemes. (NOTE: If one uses
a different funcion f , the Crank-Nicolson and Implicit Euler segments of the program will
probably need adjustments.)
Programs (MATLAB and JAVA)
ex21.m
function ex21(N,T)
%
%
%
%
Solution to exercise 2.1 e,
using both explicit and implicit schemes.
Compares with the exact solution.
example: ex21(50,1)
Dt=T/N;
t=0:Dt:T;
y(1)=0; z(1)=0; r(1)=0;
for i= 2:(N+1);
t(i)=t(i-1)+Dt;
y(i)= y(i-1)+ Dt*(1+4*y(i-1));
z(i)=(z(i-1) +Dt)/(1-4*Dt);
r(i)= (exp(4*t(i))-1)/4;
end
plot(t,r, t,y,’r--’,t,z,’g-.’);
legend(’exact solution’,’explicit scheme’,’implicit scheme’,2);
CHAPTER 2. ANSWERS CHAPTER 2
22
% Errors:
Ee= abs(y(N+1)-r(N+1));
disp(sprintf(’Error explicit/Delta t: %g ’,Ee/Dt));
Ei=abs(z(N+1)-r(N+1));
disp(sprintf(’Error implicit/Delta t: %g ’,Ei/Dt));
ex22.m
function ex22(N,T)
%
%
%
%
Solutin to exercise 2.2 e,
using both explicit and impicit schemes.
Compares with the exact solution.
example: ex22(50,1)
Dt=T/N;
t=0:Dt:T;
y(1)=1;
z(1)=1;
r(1)=1;
for i= 2:(N+1);
t(i)=t(i-1)+Dt;
y(i)= y(i-1)+ Dt*(y(i-1)+2*t(i-1)-t(i-1)*t(i-1));
z(i)=(z(i-1)+Dt*(2*t(i)-t(i)*t(i)))/(1-Dt);
r(i)= exp(t(i))+t(i)*t(i);
end
plot(t,r, t,y,’r--’,t,z,’g-.’);
legend(’exact solution’,’explicit scheme’,’implicit scheme’,2);
% Errors:
Ee= abs(y(N+1)-r(N+1));
disp(sprintf(’Error explicit/Delta t: %g ’,Ee/Dt));
Ei=abs(z(N+1)-r(N+1));
disp(sprintf(’Error implicit/Delta t: %g ’,Ei/Dt));
ex25.m
function f = ex25(R)
% Calculates the population of the United States,
% using the both the exponential model
% and the logistic model.
%
23
% example: ex25(290)
r0=5.3; a=0.03;
% exponential model:
t=1800:1900;
r=r0 * exp(a*(t-1800));
% actual population
Y=1800:10:1900;
P=[5.3, 7.2, 9.6, 12.9, 17, 23.2, 31.4, 38.6, 50.2, 63, 76.2];
% logistic model:
l= r0*R./(r0 + (R - r0)*exp(-a*(t-1800)));
plot(t,r,t,l,’g--’,Y,P,’rx’);
xlabel(’year’); ylabel(’population (millions)’);
title(’Population of the United States’);
legend(’exponential growth model’,
[’logistic model, R=’,int2str(R)],’actual population’,2);
ex27.java
/* Program for exercise 2.7,
* uses three different schemes to solve (2.38)
* and compares the solutions to the exact solution.
* example: java ex27 1 100
*/
class ex27
{
public static void main(String[] args)
{
double N, T;
double u, u1, u2, u3, Dt, Et, Em, Es;
T = Double.parseDouble(args[0]);
N = Double.parseDouble(args[1]);
System.out.print("T= " +T+" N= "+N+"\n");
Dt=T/N;
System.out.print("Dt= "+ Dt+"\n");
u=-10/(1+10*T);
u1=-10;
for (int i=1; i<N+1; i++) {
u1=( 1 - Math.sqrt(1- Dt*(Dt*u1*u1 +2*u1)))/Dt;
}
CHAPTER 2. ANSWERS CHAPTER 2
24
System.out.print("Trapes: u= "+ u1 +"\n");
u2=-10;
for (int i=1; i<N+1; i++) {
u2=( 2 - Dt*u2 - 2*Math.sqrt(1- 2*Dt*u2))/Dt;
}
System.out.print("Midpoint: u= "+ u2 +"\n");
u3=-10;
for (int i=1; i<N+1; i++) {
u3=3*( 1-((Dt*u3)/3)- Math.sqrt(1- Dt*Dt*u3*u3/3 -2*Dt*u3))/(2*Dt)
}
System.out.print("Simpson: u= "+ u3 +"\n");
Et=(u1 - u);
Em=(u2 - u);
Es=(u3 - u);
System.out.print("Exact solution: "+ u +"\n");
System.out.print("Error/Dt*Dt (Trapes): "+ Et/(Dt*Dt) +"\n");
System.out.print("Error/Dt*Dt (Midpoint): "+ Em/(Dt*Dt) +"\n");
System.out.print("Error/Dt*Dt (Simpson): "+ Es/(Dt*Dt) +"\n");
}
}
pro242.java
/*
*
*
*
*
*
*
*/
Program for Project 2.4.2.
exercise g): u’=u, u(0)=1.
Computes u at time T in three ways:
explicit Euler (u1)
implicit Euler (u2)
and Crank-Nicolson (u3)
example: java pro242 5 100
class pro242
{
public static void main(String[] args)
{
double N, T;
double u1, u2, u3, Dt, k, E_exp, E_imp, E_CN;
T = Double.parseDouble(args[0]);
N = Double.parseDouble(args[1]);
System.out.print("T: " +T+" N: "+N+"\n");
Dt=T/N;
System.out.print("Dt: "+ Dt+"\n");
25
u1=1;
u2=1;
u3= 1;
for (int i=1; i<N+1; i++) {
u1= u1 + u1*Dt;
u2= u2/(1-Dt);
u3= u3*(1 + Dt*0.5)/(1 - Dt*0.5);
}
System.out.print("Explicit Euler: u= "+ u1 +"\n");
System.out.print("Implicit Euler: u= "+ u2 +"\n");
System.out.print("Crank-Nicholson "+ u3 +"\n");
k=Math.exp(T);
E_exp=Math.abs(u1-k)/k;
E_imp=Math.abs(u2-k)/k;
E_CN=Math.abs(u3-k)/k;
System.out.print("Exact
System.out.print("Error
System.out.print("Error
System.out.print("Error
System.out.print("Error
}
solution: "+ k +"\n");
explicit/Dt "+ E_exp/Dt +"\n");
implicit/Dt "+E_imp/Dt +"\n");
Crank/Dt "+E_CN/Dt +"\n");
Crank/Dtˆ2 "+E_CN/(Dt*Dt) +"\n");
}
pro242h.java
/*
*
*
*
*
*
*
*/
Program for Project 2.4.2.
exercise h): u’=u(1-u), u(0)=10.
Computes u at time T in three ways:
explicit Euler (u1)
implicit Euler (u2)
and Crank-Nicolson (u3)
example: java pro242h 1 20
class pro242h
{
public static void main(String[] args)
{
double N, T;
double u1, u2, u3, Dt, k, C, E_exp, E_imp, E_CN;
T = Double.parseDouble(args[0]);
N = Double.parseDouble(args[1]);
System.out.print("T: " +T+" N: "+N+"\n");
Dt=T/N;
CHAPTER 2. ANSWERS CHAPTER 2
26
C=10.0/9.0;
System.out.print("Dt: "+ Dt+"\n");
u1=10;
u2=10;
u3= 10;
for (int i=1; i<N+1; i++) {
u1= u1 + u1*Dt*(1-u1);
u2=(Dt -1 + Math.sqrt(1 - 2*Dt +4*Dt*u2 +Dt*Dt))/(2*Dt);
u3=(0.5*Dt-1+Math.sqrt(1-Dt+Dt*Dt*0.25+2*Dt*u3+Dt*Dt*u3*(1-u3)))/Dt;
}
System.out.print("Explicit Euler: u= "+ u1 +"\n");
System.out.print("Implicit Euler: u= "+ u2 +"\n");
System.out.print("Crank-Nicholson "+ u3 +"\n");
k=(C*Math.exp(T))/(C*Math.exp(T)-1);
E_exp=Math.abs(u1-k);
E_imp=Math.abs(u2-k);
E_CN=Math.abs(u3-k);
System.out.print("Exact
System.out.print("Error
System.out.print("Error
System.out.print("Error
System.out.print("Error
}
}
solution: "+ k +"\n");
explicit/Dt "+ E_exp/Dt +"\n");
implicit/Dt "+E_imp/Dt +"\n");
Crank/Dt "+E_CN/Dt +"\n");
Crank/Dtˆ2 "+E_CN/(Dt*Dt) +"\n");
pro242n.java
/* Program for Project 2.4.2.
* exercise n)
* Computes u at time ’Time’ in five different ways.
* measures how long time it takes, and finds the error
* example: java pro242 1.1 20000
*/
class pro242n
{
public static void main(String[] args)
{
double N, Time;
double startTime, endTime;
double u, u0, Dt, solution, F1, F2, F3, F4;
double epsilon=0.25;
Time = Double.parseDouble(args[0]);
N = Double.parseDouble(args[1]);
Dt=Time/N;
27
u0 = Math.exp(-1/(epsilon*epsilon));
solution = Math.exp(-(1-Time)*(1-Time)/(epsilon*epsilon));
System.out.print("Exact solution: "+ solution +"\n");
// Explicit Euler
startTime = System.currentTimeMillis();
u=u0;
for (int i=1; i<N+1; i++) {
u=u+Dt*f(i*Dt,u,epsilon);
}
endTime = System.currentTimeMillis();
System.out.print("Explicit Euler: T= "+ Time + " N= "+ N+ "\n");
System.out.print(" solution: "+ u +"\n");
System.out.print(" absolute error: "+ Math.abs(u-solution) +"\n");
System.out.print(" time (milliseconds): "+ (endTime -startTime) +"\n");
// Implicit Euler
startTime = System.currentTimeMillis();
u=u0;
for (int i=1; i<N+1; i++) {
u=u/(1-Dt*f((i+1)*Dt,1,epsilon));
}
endTime = System.currentTimeMillis();
System.out.print("Implicit Euler: T= "+ Time + " N= "+ N+ "\n");
System.out.print(" solution: "+ u +"\n");
System.out.print(" absolute error: "+ Math.abs(u-solution) +"\n");
System.out.print(" time (milliseconds): "+ (endTime -startTime) +"\n");
// Crank-Nicolson
startTime = System.currentTimeMillis();
u=u0;
for (int i=1; i<N+1; i++) {
u=(u+Dt*f(Dt*i,u,epsilon)/2)/(1-Dt*f((i+1)*Dt,1,epsilon)/2);
}
endTime = System.currentTimeMillis();
System.out.print("Crank-Nicolson: T= "+ Time + " N= "+ N+ "\n");
System.out.print(" solution: "+ u +"\n");
System.out.print(" absolute error: "+ Math.abs(u-solution) +"\n");
System.out.print(" time (milliseconds): "+ (endTime -startTime) +"\n");
// Heun
startTime = System.currentTimeMillis();
u=u0;
for (int i=1; i<N+1; i++) {
F1=f(i*Dt,u,epsilon);
F2=f((i+1)*Dt,u+Dt*F1,epsilon);
u=u+Dt*(F1+F2)/2;
}
endTime = System.currentTimeMillis();
28
CHAPTER 2. ANSWERS CHAPTER 2
System.out.print("Heun: T= "+ Time + " N= "+ N+ "\n");
System.out.print(" solution: "+ u +"\n");
System.out.print(" absolute error: "+ Math.abs(u-solution) +"\n");
System.out.print(" time (milliseconds): "+ (endTime -startTime) +"\n");
// Runge-Kutta
startTime = System.currentTimeMillis();
u=u0;
for (int i=1; i<N+1; i++) {
F1=f(i*Dt,u,epsilon);
F2=f((i+0.5)*Dt,u+Dt*F1/2,epsilon);
F3=f((i+0.5)*Dt,u+Dt*F2/2,epsilon);
F4=f((i+1)*Dt,u+Dt*F3,epsilon);
u=u+Dt*(F1+2*F2+2*F3+F4)/6;
}
endTime = System.currentTimeMillis();
System.out.print("Runge-Kutta: T= "+ Time + " N= "+ N+ "\n");
System.out.print(" solution: "+ u +"\n");
System.out.print(" absolute error: "+ Math.abs(u-solution) +"\n");
System.out.print(" time (milliseconds): "+ (endTime -startTime) +"\n");
}
public static double f(double t, double u, double eps)
{
double res=u*2*(1-t)/(eps*eps);
return res;
}
}
Chapter 3
Answers Chapter 3
Exercises
3.1
a) See the program ex31.m.
b) The results will depend on the circumstances, ∆t = 0.005 is often sufficiently
small.
c) For F0 = 1 and S0 = 2 both F and S become constants. The solutions are always
periodic.
3.2
a) If F and S solve (3.74) we can write
1
2
2
1
F′ = 1 −
(2 − S) F =
− 1 (F − 1) S =
− 1 S′.
1−
F
F
S
S
b) Using integration by substitution:
Z t
Z F (t)
1 ′
1
(1 − )F dτ =
1 − du = F (t) − ln(F (t)) − (F0 − ln F0 )
F
u
0
F (0)
Z
0
t
2
( − 1)S ′ dτ =
S
Z
S(t)
S(0)
2
− 1 du = 2 ln(S(t)) − S(t) − (2 ln S0 − S0 )
u
c) Equation (3.76) can be rewritten on the form
F (t) − ln(F (t)) − (F0 − ln F0 )
F (t)−ln(F (t))−(F0 −ln F0 )
e
eF eS
F S2
= 2 ln(S(t)) − S(t) − (2 ln S0 − S0 ),
= e2 ln(S(t))−S(t)−(2 ln S0 −S0 ) ,
eF0 eS0
.
=
F0 S02
d)+e) See the program ex32.m.
29
CHAPTER 3. ANSWERS CHAPTER 3
30
3.3
a) r′ (t) = 4u3 (−v 3 ) + 4v 3 u3 = 0. The function r(t) is constant, i.e. r(t) = r(0) for
all t > 0.
b) Using Euler’s method:
un+1 = un + ∆tu′n = un − ∆tvn3
vn+1 = vn + ∆tvn′ = vn + ∆tu3n
c) See the program ex33.m.
d) Equation (3.81) holds approximately for the numerical solutions.
3.4
a) In the first equation in (3.83), divide by F and integrate on both sides:
Z
t
1 ′
F dτ
F
=
ln F (t) − ln F0
=
0
Z
t
2 − S dτ,
Z t
S dτ
2t −
0
0
In the second equation in (3.83), divide by S and integrate on both sides:
Z
t
1 ′
S dτ
S
=
ln S(t) − ln S0
=
0
Z
t
F − 1 dτ,
0
Z
t
F dτ − t
0
b) For t = T :
Z
0
S(T ) = S0 ,
T
F dτ − T = ln S(T ) − ln S0
2T −
1
T
Z
0
Z
=
0,
=
1,
T
F dτ
0
F (T ) = F0 ,
T
S dτ = ln F (T ) − ln F0
1
T
Z
0
=
0,
=
2,
T
S dτ
31
c) In the first equation in (3.89), divide by F and integrate on both sides:
Z
t
1 ′
F dτ
F
=
ln F (t) − ln F0
=
0
Z
t
(2 − S − ǫ) dτ,
Z t
S dτ
(2 − ǫ)t −
0
0
In the second equation in (3.89), divide by S and integrate on both sides:
Z
t
1 ′
S dτ
S
=
ln S(t) − ln S0
=
0
Z
t
F − 1 − δ dτ,
0
Z
0
t
F dτ − (1 + δ)t
d)
S(T ) = S0
F (T ) = F0
⇒
⇒
Z
T
F dτ = (1 + δ)T,
0
Z
T
0
S(τ ) dτ = (2 − ǫ)T
Programs (MATLAB)
ex31.m
function f = ex31(S0,F0,Dt)
% Implements the scheme (3.70).
% example: ex31(0.1,1.9,0.005)
t=0:Dt:10;
F(1)=F0;
S(1)=S0;
for i= 2:(10/Dt+1);
F(i)= F(i-1)+ Dt*(2 - S(i-1))*F(i-1);
S(i)=S(i-1) + Dt*(F(i-1)-1)*S(i-1);
end
subplot(2,1,1) ; plot(t,F,t,S,’--’);legend(’F’,’S’);xlabel(’t’);
subplot(2,1,2) ; plot(F,S); xlabel(’F’); ylabel(’S’);
ex32.m
function f = ex32(S0,F0,Dt)
% Implements the scheme (3.70).
% example: ex32(0.1,1.9,0.005)
CHAPTER 3. ANSWERS CHAPTER 3
32
t=0:Dt:10;
F(1)=F0;
S(1)=S0;
K(1)=exp(F0)*exp(S0)/(F0*S0*S0)
for i= 2:(10/Dt+1);
F(i)= F(i-1)+ Dt*(2 - S(i-1))*F(i-1);
S(i)=S(i-1) + Dt*(F(i-1)-1)*S(i-1);
K(i)=exp(F(i))*exp(S(i))/(F(i)*S(i)*S(i));
end
Ek=(K-K(1))/K(1);
plot(t,Ek);xlabel(’t’); ylabel(’Error K_n’);
E = (K(i)-K(1))/(K(1)*Dt);
disp(sprintf(’N= %g, E/Dt= %g’,10/Dt,E));
ex33.m
function f = ex33(u0,v0,N,T)
% Implements the scheme (3.82)
% example: ex33(1.2,2.3,1000,2)
Dt=T/N;
t=0:Dt:T;
u(1)=u0;
v(1)=v0;
r0=u0ˆ4 + v0ˆ4
for i= 2:(N+1);
u(i)= u(i-1) - Dt*v(i-1)ˆ3;
v(i)=v(i-1) + Dt*u(i-1)ˆ3;
end
rt=u(i)ˆ4 + v(i)ˆ4
subplot(2,1,1) ; plot(t,u,t,v,’--’);xlabel(’t’);legend(’u’,’v’);
subplot(2,1,2) ; plot(u,v); xlabel(’u’); ylabel(’v’);
Chapter 4
Answers Chapter 4
Exercises
4.1
See Figure 4.1.
a) f (0) = e0 − 1 = 0
b) Newton’s method; (f ′ (x) = ex ):
x0
= 1
x1
= 1−
x2
x3
x4
e1 − 1
= 0.367879
e1
e0.367879 − 1
= 0.367879 −
= 0.060080
e0.367879
= 0.001769
= 0.000002
4.2
See Figure 4.1.
a) f (0) = 0 − sin 0 = 0
x0
=
1
x1
=
x2
=
1 − sin 1
= 0.655145
1 − cos 1
0.433590
x3
x4
=
=
0.288148
0.191832
x0
=
1
1−
b) f (0) = 1 − cos 0 = 0
33
CHAPTER 4. ANSWERS CHAPTER 4
34
x
e −1
x−sin(x)
2
0.5
1.5
1
f
f
0.5
0
0
−0.5
−1
−1
−0.5
0
x
0.5
1
0.5
1
−0.5
−1
−0.5
0
x
0.5
1−cos(x)
0.5
0.4
f
0.3
0.2
0.1
0
−1
−0.5
0
x
Figure 4.1: Sketches of the functions from exercise 4.1. and 4.2.
x1
=
x2
=
1 − cos 1
= 0.453678
sin 1
0.222866
x3
x4
=
=
0.110969
0.055427
1−
4.3
a)
x0
=
3
x1
=
3−
x2
=
x3
x4
=
=
13
32 − 4
=
2·3
6
313
= 2.006410256
156
2.00001024
2.00000000
b)
x0
=
1
x1
=
1−
x2
=
1
4
12
1
=
2·1
2
1
35
x3
=
x3
=
x0
=
1
8
1
16
d)
x1
x2
x3
x4
1
5
16
=
1−
5 · 15
6
2
5
=
6
3
5
=
6
4
5
=
6
=
4.4
a) Inserting x = y = 0:
ey − x = e0 − 0 = 1
x2 − y = 02 − 0 = 0
b) (x0 , y0 ) = (0.5, 0.5), (x1 , y1 ) = (0.9061, 0.6561), (x2 , y2 ) = (0.7701, 0.5746)
(NOTE: The system will converge towards a different solution than the one in exercise a.)
4.5
a) Explicit Euler:
un+1 = un + ∆te−un
b) Implicit Euler:
un+1 − ∆te−un+1 = un
c) See the program ex45.m.
d) Using u(t) = ln(1 + t):
u′ (t)
=
u(0)
=
e)+f) See the program ex45.m.
1
= e− ln(1+t) = e−u
1+t
ln(1 + 0) = 0
CHAPTER 4. ANSWERS CHAPTER 4
36
4.6
a) Newton’s method:
xk+1 = xk −
c − x1k
f (xk )
= (2 − cxk )xk
=
x
−
k
1
f ′ (xk )
x2
k
b)
n=1
n=2
n=3
n=4
xn
0.24
0.2496
0.24999936
0.25000000
errorn
0.01
4 · 10−4
6.4 · 10−7
less than 10−11
Projects
4.8; Convergence of Newton’s Method
a) Newtons method for f (x) = 0 when f (x) = x2 − 4:
b) The ratio ck =
x0
=
3.00000000000000
x1
x2
=
=
2.16666666666667
2.00641025641026
x3
x4
=
=
2.00001024002621
2.00000000002621
c0
c1
c2
=
=
=
0.16666666666667
0.23076923076923
0.24920127795669
c3
=
0.24999625922877
|ek+1 |
:
e2k
It appears that ck converges towards c = 0.25. This means |ek+1 | ≈ 0.25e2k .
c) See figure 4.2.
g(0) = e0 − cos(0) = 1 − 1 = 0
d) Newtons method for g(x) = 0:
x0
x1
=
=
0.25000000000000
0.04423602555409
x2
x3
=
=
0.00182264870657
0.00000331198793
x4
=
0.00000000001097
37
2
1.8
ex
cos(x)
1.6
1.4
1.2
1
0.8
0.6
0.4
−0.6
−0.4
−0.2
0
x
0.2
0.4
0.6
Figure 4.2: The function g(x) = ex − cos(x) is zero at the point where the two lines
intersect, at x = 0.
c0
=
0.70777640886547
c1
c2
=
=
0.93143117823681
0.99697163563298
c3
=
0.99999172671747
c converges towards 1, so the convergence is quadratic:
|ek+1 | ≈ e2k
e) Newtons method for f (x) = x2 − 4:
xk+1 = xk −
f (x)
x2 − 4
x2 + 4
= xk − k
= k
′
f (x)
2xk
2xk
f)
h′ (x) =
(x2 + 4)′ (2x) − (2x)′ (x2 + 4)
(2x)(2x) − 2(x2 − 4)
x2 − 4
=
=
2
2
(2x)
4x
2x2
g) h′ (x) is nonnegative for all x ≥ 2. This means that the function h is increasing for
x ≥ 2, and as h(2) = 2, h(x) will be greater than or equal to 2 for all x ≥ 2.
h) Using the result from g: If, for any k, xk ≥ 2 then xk+1 ≥ 2, since xk+1 = h(xk ).
CHAPTER 4. ANSWERS CHAPTER 4
38
i) If xk is always 2 or more, then (xk − 2) is always positive. This means we can
replace ek with |ek |.
j)
|ek+1 | = xk+1 − 2
x2k + 4
−2
=
2xk
(xk − 2)2
=
2xk
2
ek
=
2xk
k) We know from exercise h that xk ≥ 2. Combining this with the result from exercise
j gives the result
e2
1
|ek+1 | = k ≤ e2k .
2xk
4
This is consistent with the ratio ck converging towards 0.25 in exercise b.
l) Combining (4.207) and (4.208):
ek+1
= xk+1 − x∗
f (xk )
= xk − ′
− x∗
f (xk )
f (xk )
= ek − ′
f (xk )
ek f ′ (xk ) − f (xk )
=
f ′ (xk )
m) The Taylor series for f on the interval (x∗ , xk ) is:
f (x∗ )
= f (xk ) + (x∗ − xk )f ′ (xk ) +
= f (xk ) − ek f ′ (xk ) +
(x∗ − xk )2 ′′
f (ξ)
2
e2k ′′
f (ξ)
2
n) We know that x∗ is a root of f so f (x∗ ) = 0. Inserting this into the result from
exercise m gives:
0 = f (xk ) − ek f ′ (xk ) +
ek f ′ (xk ) − f (xk ) =
e2k ′′
f (ξ)
2
e2k ′′
f (ξ)
2
o) Combining equations (4.212) and (4.214):
ek+1 =
f ′′ (ξ) 2
ek f ′ (xk ) − f (xk )
= ′
e
′
f (xk )
2f (xk ) k
39
1
0.8
cosh(x)−1
sinh(x)
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
−1
−0.8
−0.6
−0.4
−0.2
0
x
0.2
0.4
0.6
0.8
1
Figure 4.3: Functions (4.217) and (4.218).
p) Using (4.210), (4.211) and ek = |ek |:
|ek+1 | =
β 2
|f ′′ (ξ)| 2
e ≤
e
|f ′ (xk )| k
2α k
q) See figure 4.3.
r) From figure 4.3 we can easily see that the tangent of the funtion at x = 1 will come
closer to the desired point for the function sinh(x) than for the funtion (cosh(x) −
1).
s)
f ′ (x)
=
sinh(x),
f ′′ (x)
g ′ (x)
g ′′ (x)
=
=
=
cosh(x), cosh(0) = 1
cosh(x), cosh(0) = 1
sinh(x), sinh(0) = 0
sinh(0) = 0
We know from exercise o that
ek+1 =
f ′′ (ξ) 2
e
2f ′ (xk ) k
where ξ ∈ [x∗ , xk ]. For g(x) this means the error will decrease rapidly, since g ′′ (ξ)
goes towards zero as we approach the exact solution. For f (x) however, we instead
have f ′ (xk ) becoming very small, and the error hardly decreases at all.
CHAPTER 4. ANSWERS CHAPTER 4
40
1.5
1
0.5
f
0
−0.5
−1
−1.5
−2
−1.5
−1
−0.5
0
0.5
1
1.5
x
Figure 4.4: f (x) = 1 − x2
t) Newton’s method for f (x) = cosh(x) − 1:
x0
x1
x2
x3
x4
= 1.0000
= 0.5379
= 0.2752
= 0.1385
= 0.0694
e1 /e0
e2 /e1
e3 /e2
e4 /e3
= 0.5397
= 0.5117
= 0.5031
= 0.5008
Newton’s method for g(x) = sinh(x):
x0 = 1.0000
x1 = 0.2384
x2 = 4.416 · 10−3
x3 = 2.871 · 10−8
x4 = 9.926 · 10−24
e1
e30
= 0.2384
= 0.3259
= 0.3333
= 0.4193
e2 /e31
e3 /e32
e4 /e33
u) Newton’s method for f (x) = 1 − x2 does not work if we use x0 = 0, resulting in
f ′ (x) = 0. In the graphical analysis this means we are looking for the point where
the tangent to the maxima of f (x) intersects the x-axis. Obviously this point does
not exist. If x0 is close to zero, then the tangent will intersect the x-axis far away
from the solution at x = ±1, and convergence will be slow (see fig 4.4).
v) When we choose x0 = 0 we find that x1 = 2, which is a solution. As seen in figure
4.5, Newton’s method ’overshoots’ the solutions close to x0 and we end up with an
answer that is correct, but may not be the one we are looking for.
w) For f (x) = x − x3 Newton’s method can be written as
xk+1 = xk −
f (xk )
xk − x3k
−2x3k
= xk −
=
.
2
′
f (xk )
1 − 3xk
1 − 3x2k
41
2.5
2
1.5
f
1
0.5
0
−0.5
−1
−1.5
−1.5
−1
−0.5
0
0.5
1
1.5
2
2.5
x
Figure 4.5: f (x) = (x + 1)(x − 1)(x − 2)
√
Putting x0 = 1/ 5 we get:
x1 =
1
−2 53/2
and
x2 =
1−
3
5
1
2 53/2
1−
3
5
1
= −√ ,
5
1
=√ .
5
This means that instead converging towards a solution, the answers alternate between two values; x = ± √15 , as seen in figure 4.6.
Programs (MATLAB)
ex45.m
function ex45(Dt);
% Solves the expression u’=exp(-u), using four different numerical tecniques.
% Compares with the exact solution.
% example: ex45(0.05)
eE(1)=0; iE(1)=0;
t(1)=0; S(1)=0;
Se(1)=0; Sf(1)=0;
for i= 2:(1/Dt+1);
t(i)=(i-1)*Dt;
% exact solution
S(i)=log(1+t(i));
CHAPTER 4. ANSWERS CHAPTER 4
42
0.4
f
0.2
0
−0.2
−0.4
−1
−0.5
0
0.5
1
x
Figure 4.6: f (x) = x − x3
% explicit Euler
eE(i)=eE(i-1)+Dt*exp(-eE(i-1));
% implicit Euler (using Newton)
n_1=iE(i-1);
while(abs(f(n_1,iE(i-1),Dt))>10ˆ(-6))
n_1=n_1-f(n_1,iE(i-1),Dt)/df(n_1,Dt);
end
iE(i)=n_1;
% scheme e (using Newton)
e_1=Se(i-1);
while(abs(f_e(e_1,Se(i-1),Dt))>10ˆ(-6))
e_1=e_1-f_e(e_1,Se(i-1),Dt)/df_e(e_1,Dt);
end
Se(i)=e_1;
% scheme f (using Newton)
f_1=Sf(i-1);
while(abs(f_f(f_1,Sf(i-1),Dt))>10ˆ(-6))
f_1=f_1-f_f(f_1,Sf(i-1),Dt)/df_f(f_1,Sf(i-1),Dt);
end
Sf(i)=f_1;
end
disp(sprintf(’Error:
disp(sprintf(’Error:
disp(sprintf(’Error:
disp(sprintf(’Error:
explicit Euler:
implicit Euler:
scheme e:
scheme f:
%g’,abs(S(i)-eE(i))));
%g’,abs(S(i)-iE(i))));
%g’,abs(S(i)-Se(i))));
%g’,abs(S(i)-Sf(i))));
plot(t,S,t,eE,’r--’,t,iE,’g:’,t,Se,’kx’,t,Sf,’c+’);
xlabel(’t’);
legend(’Exact solution’,’Explicit Euler’,’Implicit Euler’,’Scheme e’,’Schem
43
function val = f(u_n1, u_n, Dt);
val = u_n1-Dt*exp(-u_n1)-u_n;
function der = df(u_n1,Dt);
der = 1+Dt*exp(-u_n1);
function val_e = f_e(u_n1, u_n, Dt);
val_e=u_n1-Dt*exp(-u_n1)*0.5-u_n-Dt*exp(-u_n)*0.5;
function der_e = df_e(u_n1,Dt)
der_e = 1+Dt*0.5*exp(-u_n1);
function val_f = f_f(u_n1, u_n, Dt);
val_f = Dt*exp(-0.5*u_n1-0.5*u_n)-u_n1+u_n;
function der_f = df_f(u_n1, u_n, Dt)
der_f = -1-Dt*0.5*exp(-0.5*u_n1-0.5*u_n);
44
CHAPTER 4. ANSWERS CHAPTER 4
Chapter 5
Answers Chapter 5
Exercises
5.1
a) Constant approximation: y(t) = 4.
b) Linear approximation: y(t) = 28 − 4t.
c) Quadratic approximation: y(t) = 28 − 4t + 0t2 .
5.2
a) Linear model: p(t) = 58.6 − 6t.
Years ti
zi = ln(yi )
c)
1
4.01
2
3.86
3
3.63
4
3.56
5
3.40
d) q(t) = 4.13 − 0.15t
e) p(t) = 62.2e−0.15t
5.3
a) c(n) = 0.005 + 0.00000043n
b) c(106 ) ≈ 0.435, c(107 ) ≈ 4.305
5.4
a) T (n) = 9.15 · 10−4 + 7.35 · 10−7 n
b) T (0) = α = 9.15 · 10−4 is the time to send a vector of length 0. This is not the
same as not sending anything at all, which takes no time.
Consider the difference between not sending a vector at all (T = 0), and sending a
vector of length zero (T = α).
c) The bandwidth is 0.087 gigabits per second.
45
CHAPTER 5. ANSWERS CHAPTER 5
46
5.5
a)
d
dα
Z
#
"Z
Z b
b
1
F (α, t) dt
F (α + ε, t) dt −
= lim
ε→0 ε
a
a
Z b
F (α + ε, t) − F (α, t)
lim
=
ε→0
ε
a
Z b
d
F (α, t) dt
=
a dα
b
F (α, t) dt
a
b)
L(α)
=
=
=
R(α) =
d
dα
d
dα
=
b
(α − p(t))2 dt
a
"Z
b
2
α dt −
a
2α(b − a) − 2
Z
b
a
=
Z
Z
Z
Z
b
2αp(t) dt +
Z
b
(p(t)) dt
a
a
b
p(t) dt
a
d
(α − p(t))2 dt
dα
b
d 2
(α − 2αp(t) + (p(t))2 ) dt
a dα
Z b
p(t) dt
2α(b − a) − 2
a
5.6
Constant approximations:
a)
α=
1
π−0
Z
π
0
1
sin(t) dt = 1.006
100
1+
b)
α=
1
e−1 − 0
Z
1
π−0
Z
e−1
et dt = 1.209
0
c)
α=
0
π
√
t dt = 1.182
2
#
47
2.5
y(t)
Quadratic
Taylor
2
1.5
1
0.5
−1
−0.8
−0.6
−0.4
−0.2
0
0.2
0.4
0.6
0.8
1
t
Figure 5.1: The function y(t) = et , approximated in two different ways.
5.7
Linear:
a) y(t) ≈ 0.87 + 1.69t
b) y(t) ≈ 0.94 − 0.62t
c) y(t) ≈ 1.41 − 0.48t
5.8
Quadratic:
a) y(t) ≈ 1.01 + 0.851t + 0.839t2
b) y(t) ≈ 1.00 − 0.937t + 0.315t2
c) y(t) ≈ 2.11 − 1.46t + 0.327t2
5.9
a) Quadratic least squares approximation: y(t) ≈ 1 + 1.1t + 0.54t2
b) Taylor series expansion: y(t) ≈ e0 + te0 +
c) See figure 5.1.
t2 0
2e
=1+t+
t2
2
CHAPTER 5. ANSWERS CHAPTER 5
48
Projects
5.5; Computing Coefficients
a) Using (5.153):
Z
tn+1
tn
y ′ (t)
t=t
= ln y(tn+1 ) − ln y(tn )
dt = [ln y(t)]t=tn+1
n
y(t)
b) Using equation (5.148) we can replace
Z
tn+1
tn
y ′ (t)
y(t)
Z tn+1
y ′ (t)
α dt
dt =
y(t)
tn
(tn+1 − tn )α
α
with α in the equation from exercise a:
=
ln y(tn+1 ) − ln y(tn )
=
ln y(tn+1 ) − ln y(tn )
ln y(tn+1 ) − ln y(tn )
tn+1 − tn
=
c)
α0
=
0.01476
α1
α2
=
=
0.01607
0.01693
α3
α4
=
=
0.01775
0.01888
d) With these numbers we get α = 0.01688.
e) See figure 5.2.
f) Using γ = −α/β:
y ′ (t)
= αy(t)(1 − y(t)/β)
= αy(t) + γy 2 (t)
′
y (t)
y(t)
= α + γy(t)
g) From (5.154):
Z
tn+1
tn
y ′ (t)
dt = ln y(tn+1 ) − ln y(tn )
y(t)
From (5.159):
Z
tn+1
tn
y ′ (t)
dt =
y(t)
Z
tn+1
tn
(α + γy(t)) dt = α(tn+1 − tn ) + γ
Z
tn+1
tn
y(t) dt
49
6
p(t)=2.555e0.01685t
p(t)=2.555e0.01704t
5.5
5
p(t)
4.5
4
3.5
3
2.5
0
5
10
15
20
25
30
35
40
45
50
t
Figure 5.2: Two different functions p(t), from (5.83) and (5.158).
h) We can use the trapezoid method to approximate the integral from g:
ln y(tn+1 ) − ln y(tn ) = α(tn+1 − tn ) + γ
ln(y(tn+1 )/y(tn ))
ln(y(tn+1 )/y(tn ))
(tn+1 − tn )
i)
year
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
n
0
1
2
3
4
5
6
7
8
9
10
y(tn )
5.284
5.367
5.450
5.531
5.611
5.691
5.769
5.847
5.925
6.003
6.080
Z
tn+1
y(t) dt
tn
1
≈ α(tn+1 − tn ) + γ(tn+1 − tn ) (y(tn+1 ) + y(tn ))
2
γ
≈ α + (y(tn+1 ) + y(tn ))
2
cn = ln(y(tn+1 )/y(tn ))
0.0156
0.0153
0.0148
0.0144
0.0142
0.0136
0.0134
0.0133
0.0131
0.0127
dn = 21 (y(tn+1 ) + y(tn ))
5.3255
5.4085
5.4905
5.5710
5.6510
5.7300
5.8080
5.8860
5.9640
6.0415
j) By minimizing F (α, γ) we find the values of α and γ for which α+γdn is the linear
least squares approximation to the dataset cn .
CHAPTER 5. ANSWERS CHAPTER 5
50
k)
∂F
∂α
= 0:
∂F
∂α
=
0
=
0
(α + γdn − cn ) =
0
9
∂ X
(α + γdn − cn )2
∂α n=0
2
9
X
n=0
10α +
9
X
dn
n=0
∂F
∂γ
!
γ
=
9
X
cn
n=0
= 0:
∂F
∂γ
9
∂ X
(α + γdn − cn )2
∂γ n=0
2
9
X
n=0
9
X
n=0
dn
(α + γdn − cn )dn
!
α+
9
X
d2n
n=0
!
γ
=
0
=
0
=
0
=
9
X
cn dn
n=0
P9
P9
l) From the table from exercise i we calculate 0 dn = 56.8760, 0 cn = 0.1403,
P9
P9 2
0 dn = 324.008, and
0 cn dn = 0.7960. Solving (5.166) as a system of two
equations with two unknowns is trivial and gives α ≈ 0.0368, β ≈ −0.0040.
m) β = −α/γ ≈ −0.0368/(−0.0040) = 9.2.
n) The solution to the logistic model with y0 = 6.08 is:
y(t) =
=
=
o) See figure 5.3.
y0 +
y0 β
−αt
e (β
− y0 )
6.08 · 9.2
6.08 + e−0.0368t (9.2 − 6.08)
55.94
6.08 + 3.12e−0.0368t
51
9.5
y(t)
p(t)
9
Population
8.5
8
7.5
7
6.5
6
2000
2005
2010
2015
2020
2025
2030
2035
2040
2045
2050
Year
Figure 5.3: Population growth for 50 years, starting at year 2000, using equation 5.101
(p) and 5.169 (y).
52
CHAPTER 5. ANSWERS CHAPTER 5
Chapter 6
Answers Chapter 6
Exercises
6.1+6.2
Algorithm for solving quadratic equations, with input data
checks.
Quadratic (a, b, c)
if a = 0 and b = 0 and c 6= 0
write error message
else if a = 0
return −c/b
else
r1 = (−b + sqrt(b2 − 4ac))/(2a)
r2 = (−b − sqrt(b2 − 4ac))/(2a)
if r1 = r2
return r1
else
return r1 , r2
end if
end if
53
54
CHAPTER 6. ANSWERS CHAPTER 6
6.3
Algorithm for solving quadratic equations, not using imaginary
numbers.
Quadratic (a, b, c)
if a = 0 and b = 0 and c 6= 0
write error message
else if a = 0
return −c/b, 0
else if b2 ≥ 4ac
r1 = (−b + sqrt(b2 − 4ac))/(2a), 0
r2 = (−b − sqrt(b2 − 4ac))/(2a), 0
if r1 = r2
return r1
else
return r1 , r2
else
r1 = −b/(2a), sqrt(4ac − b2 )/(2a)
r2 = −b/(2a), −sqrt(4ac − b2 )/(2a)
if r1 = r2
return r1
else
return r1 , r2
end if
6.5
Use the following pseudocode:
∆t = T /N
u0 = U0
write (0, u0 ) to file
for i = 1, . . . , N
ui = heun(f, ui−1 , ∆t, 1)
write (i∆t, ui ) to file
end for
The number of f -function evaluations is now 3N instead of 3
PN
i=1
i.
55
6.6
Generalized Heun’s method.
heun(f, U0 , ∆t, N )
u = U0
for n = 0, . . . , N − 1
v = f (u, n∆t)
un+1 ← un + ∆t
2 [v + f (un + ∆tv, (n + 1)∆t)]
end for
return u0 , u1 , . . . , uN
Projects
6.7.1; Computing the volume of a Cylindrical Container
a)
V
=
Z
H
2π
H
Z
Z
R(x)
r dr dθ dx
0
0
0
Z
Z
2π
1
2
[R(x)] dθ dx
2
0
0
2π
Z H
θ
2
=
[R(x)]
dx
2
0
θ=0
Z H
2
[R(x)] dx
= π
=
0
b)
R(x)
if x ≤ 3 then R = x
else if 3 ≤ x ≤ 5 then R = 3
else if 5 ≤ x ≤ 6 then R = 13 − 2x
else if 6 ≤ x then R = 1
Return R
c)
CHAPTER 6. ANSWERS CHAPTER 6
56
volume(R(x),H,n)
x=0
Dx = H
n
2
2
V= 21 [R(0)] + [R(H)]
for i = 1, . . . , n − 1
x = x + Dx
2
V = V + [R(x)]
end for
V=V*3.14
Return V
d) Se the program p61.c.
e) Se the program p61e.c. This program uses Algorihm 6.2. from the book. This
version is easier to modify for other applications.
6.7.2; A Class Hierarchy for Scalar ODE Solvers
a) class ODESolver_prm
data:
u0, f, Dt
tstop
method
...
methods
constructor()
create()
default()
read()
write()
b) class ODESolver
data:
prm
methods:
constructor(ODESolver_prm p)
prm = p
calculate()
c) class Heun, subclass of ODESolver
data:
methods:
constructor(ODESolver_prm p)
ODESolver.constructor.(p)
calculate()
u[0]=prm.u0
n = prm.tstop / prm.Dt
57
for i=1,..,n
v=f(u[i])
u[i+1]=u[i]+prm.dt(v+f(u[i] + prm.dt*v ))/2
end for
return u
d)-f) For implementatons in Python see ODE.py. The Java and C++ classes are shown
in their own sections. (The C++ classes use a slightly different scheme.)
g) We can test the programs using the problem from exercise 2.1; u′ (t) = 1+4r(t), r(0) =
0. We know that the analythical solution is
r(t) =
1 4t
(e − 1)
4
which gives the results r(0.5) = 1.597 and r(1) = 13.400. We compare this to the
results we get by running p62.py:
>python p62.py -d 0.01 -s 1 -u 0 -f ’1+4*u’ -m RK
Dt=0.01 tstop=1 npoints=100 u0=0 f=’1+4*u’ method=RK
13.3995310153
>python p62.py -d 0.01 -s 0.5 -u 0 -f ’1+4*u’ -m Heun
Dt=0.01 tstop=0.5 npoints=50 u0=0 f=’1+4*u’ method=Heun
1.596308904
6.7.3; Software for Systems of ODEs
a)
Heun’s method for systems of ODEs,
storing computed values in an array.
heun(f, g, Y0 , Z0 , ∆t, N )
y0 = Y0
z0 = Z0
for n = 0, . . . , N − 1
v = f (yn , zn )
w = g(yn , zn )
yn+1 = yn + ∆t
2 [v + f (yn + ∆tv, zn + ∆tw)]
zn+1 = zn + ∆t
2 [w + g(yn + ∆tv, zn + ∆tw)]
end for
return (y0 , y1 , . . . , yN ), (z0 , z1 , . . . , zN )
CHAPTER 6. ANSWERS CHAPTER 6
58
Heun’s method for systems of ODEs,
returning only the final values.
heun(f, g, Y0 , Z0 , ∆t, N )
y0 = Y0
z0 = Z0
for n = 0, . . . , N − 1
v = f (y, z)
w = g(y, z)
y2 = y + ∆t
2 [v + f (y + ∆tv, z + ∆tw)]
z2 = z + ∆t
2 [w + g(y + ∆tv, z + ∆tw)]
y = y2
z = z2
end for
return (y, z)
b)+c) For implementation in Python, see ODEs.py.
d) We can test this program using the problem from exercise 3.1. Simply run p63.py
a few times with different values for tstop, e.g..
>python p63.py -d 0.001 -s 2 -y 1.9 -z 0.1
-f ’(2-v)*u’ -g ’(u-1)*v’
and compare the results with the arrays generated by ex31.m.
Programs (C,C++, Python, Java )
p61.c
/* A simple c program showing implementations of the
* functions from project 6.1.
*/
#include <stdio.h>
double R(double x);
double volume(double H, int n, double (*Rfunk)(double x));
int main (int argc, char *argv[]) {
double result;
result = volume(8, 1000, R);
printf("Volume: %lf\n", result);
}
double volume(double H, int n, double (*Rfunk)(double x)){
double Dx, V, x;
int i;
Dx=H/n;
x=0;
59
printf("Dx: %lf\n", Dx);
V=0.5*((*Rfunk)(0)*(*Rfunk)(0)+(*Rfunk)(H)*(*Rfunk)(H));
for (i=1; i<n; i++){
x=x+Dx;
V=V+(*Rfunk)(x)*(*Rfunk)(x);
}
V=3.14159*Dx*V;
return V;
}
double R(double x){
double R;
if (x <= 3) R=x;
else if (x <= 5) R=3;
else if (x <= 6) R=13-2*x;
else R=1;
return R;
}
p61e.c
/* This program does the same as program p61.c,
* but using Algorithm 6.2.
*/
#include <stdio.h>
double f(double x);
double trapezoidal(double a, double b, int n, double (*function)(double x));
double R(double x);
int main (int argc, char *argv[]) {
double result;
result = trapezoidal(0, 8, 100, f);
printf("Volume: %lf\n", result);
}
double trapezoidal(double a, double b, int n, double (*function)(double x)){
double h, s, x;
int i;
h=(b-a)/n;
s=0;
x=a;
for (i=1; i<n; i++){
x=x+h;
s=s+(*function)(x);
}
s=s+0.5*((*function)(a)+(*function)(b));
s=h*s;
return s;
CHAPTER 6. ANSWERS CHAPTER 6
60
}
double R(double x){
double R;
if (x <= 3) R=x;
else if (x <= 5) R=3;
else if (x <= 6) R=13-2*x;
else R=1;
return R;
}
double f(double x){
double res;
res= 3.1415*R(x)*R(x);
return res;
}
ODE.py
import sys
from Numeric import *
class ODE:
"""
Base class for numerical methods for ODEs.
"""
def __init__(self, p):
self.prm = p # ODE_prm object
def calculate(self):
"""Perform integration."""
# to be implemented in subclasses
return "ODE.calculate; not impl. in subclass"
class Euler(ODE):
"""
Euler’s method.
"""
def __init__(self, p):
ODE.__init__(self, p)
def calculate(self):
p = self.prm; f = p.f; n = p.npoints; u0 = p.u0; Dt=p.dt;
u = zeros(n+1, Float)
u[0]=u0 #initial condition
# advance n steps:
for i in range (0,n,1):
u[i+1] = u[i]+Dt*f(u[i])
61
return u
class RK(ODE):
"""
4. Order Runge-Kutta.
"""
def __init__(self, p):
ODE.__init__(self, p)
def calculate(self):
p = self.prm; f = p.f; n = p.npoints; u0 = p.u0; Dt=p.dt;
u = zeros(n+1, Float)
u[0]=u0 #initial condition
# advance n steps:
for i in range (0,n,1):
F1 = f(u[i])
F2 = f(u[i]+Dt*0.5*F1)
F3 = f(u[i]+Dt*0.5*F2)
F4 = f(u[i]+Dt*F3)
u[i+1]=u[i] + Dt*(F1 + 2*F2 + 2*F3 +F4)/6
return u
class Heun(ODE):
"""
Heun’s method, 2. order Runge-Kutta.
"""
def __init__(self, p):
ODE.__init__(self, p)
def calculate(self):
p = self.prm; f = p.f; n = p.npoints; u0 = p.u0; Dt=p.dt;
u = zeros(n+1, Float)
u[0]=u0 #initial condition
# advance n steps:
for i in range (0,n,1):
v = f(u[i])
u[i+1] = u[i]+0.5*Dt*(v+f(u[i] + Dt*v))
return u
class ODE_prm:
"""
Holds all parameters needet to initiate objects
in the ODE hierarcy.
"""
def __init__(self):
self.default()
return
CHAPTER 6. ANSWERS CHAPTER 6
62
def default(self):
"""assign appropriate default values to all parameters"""
self.tstop = 1
self.u0 = 1
self.dt = 0.01
self.f = Function(’1+x’, independent_variable=’x’)
self.method = "Heun"
self.npoints = int(self.tstop/self.dt)
def read(self, argv=sys.argv[1:]):
# manual parsing
for i in range(0,len(argv),2):
if argv[i] == "-s": self.tstop = float(argv[i+1])
if argv[i] == "-d": self.dt = float(argv[i+1])
if argv[i] == "-f": self.f = Function(argv[i+1])
if argv[i] == "-m": self.method = argv[i+1]
if argv[i] == "-u": self.u0 = float(argv[i+1])
self.npoints = int(self.tstop/self.dt)
def write(self):
print "Dt=%g tstop=%g npoints=%g u0=%g f=’%s’ method=%s" % \
(self.dt, self.tstop, self.npoints, self.u0, \
self.f.__name__, self.method)
def create(self):
"""Create subclass of ODE"""
code = "i = %s(self)" % self.method
exec(code) # turn string into Python code
return i
class Function:
"""
Unified treatment of functions; strings or function objects.
Examples on usage:
def myfunc(u):
return 1+x
f = Function(myfunc, ’x’)
v = f(1.2)
# attach Python function
f = Function(’1+t’, ’t’)
v = f(1.2)
# specify function by string
"""
def __init__(self, f, independent_variable=’u’):
self.f = f # expression or function object
self.var = independent_variable # ’x’, ’t’ etc.
if type(f) == type(""):
self.f_is_string = 1
self.__name__ = self.f
else:
# function object:
63
self.f_is_string = 0
self.__name__ = self.f.__name__
def __call__(self, u):
if self.f_is_string:
exec("%s = %g" % (self.var, u))
return eval(self.f)
else:
return self.f(u)
p62.py
#!/usr/bin/env python
from ODE import *
# give access to library
from math import *
from sys import *
o=ODE_prm()
o.read(sys.argv[1:])
o.write()
i=o.create()
result = i.calculate()
print result[-1]
Java classes for Project 6.7.2
import java.lang.*;
interface Func { // base class for functions f(x)
public double f (double x); // default empty implementation
}
class ODESolver {
public ODESolver_prm prm;
public ODESolver (ODESolver_prm p)
{ prm = p; }
public double [] calculate ()
{
System.out.println("ODE.calculate; not impl. in subclass");
double k [] = new double[1];
return k;
}
}
class Heun extends ODESolver {
public Heun (ODESolver_prm p)
{ super(p); }
public double [] calculate ()
CHAPTER 6. ANSWERS CHAPTER 6
64
{
double dt = prm.dt; double u0 = prm.u0; int n = prm.n;
Func f = prm.f;
double u [] = new double[n+1];
u[0] = u0; // initial condition
// advance n steps:
for (int i = 0; i < n; i++) {
double v=f.f(u[i]);
u[i+1] = u[i] + 0.5*dt*(v + f.f( u[i] + dt*v ));
}
return u;
}
}
class Euler extends ODESolver {
public Euler (ODESolver_prm p)
{ super(p); }
public double [] calculate ()
{
double dt = prm.dt; double u0 = prm.u0; int n = prm.n;
Func f = prm.f;
double u [] = new double[n+1];
u[0] = u0; // initial condition
// advance n steps:
for (int i = 0; i < n; i++) {
u[i+1] = u[i] + dt*f.f(u[i]);
}
return u;
}
}
class RK extends ODESolver {
public RK (ODESolver_prm p)
{ super(p); }
public double [] calculate ()
{
double dt = prm.dt; double u0 = prm.u0; int n = prm.n;
Func f = prm.f;
double u [] = new double[n+1];
u[0] = u0; // initial condition
// advance n steps:
for (int i = 0; i < n; i++) {
double F1 = f.f(u[i]);
double F2 = f.f(u[i] + dt*0.5*F1);
double F3 = f.f(u[i] + dt*0.5*F2);
double F4 = f.f(u[i] + dt*F3);
u[i+1] = u[i] + dt*(F1 + 2*F2 + 2*F2 + F4)/6;
65
}
return u;
}
}
class ODESolver_prm {
public double u0, dt, tstop;
public Func f;
public int n;
public String method;
public ODESolver_prm ()
{
/* default values */
u0=1; dt=0.01; tstop=1; f = new f2();
method = "Heun";
n= (int) (tstop/dt);
}
public void read (String argv[])
{
int i;
for (i = 0; i < argv.length; i=i+2) {
if (argv[i].compareTo("-s") == 0) {
tstop = Double.valueOf(argv[i+1]).doubleValue();
}
if (argv[i].compareTo("-d") == 0) {
dt = Double.valueOf(argv[i+1]).doubleValue();
}
if (argv[i].compareTo("-u") == 0) {
u0 = Integer.valueOf(argv[i+1]).intValue();
}
if (argv[i].compareTo("-m") == 0) {
method = argv[i+1];
}
}
n= (int) (tstop/dt);
}
public void write ()
{ System.out.println("Dt=" + dt + " tstop=" + tstop + " u0=" + u0
" method=" + method);
}
public ODESolver create ()
{
ODESolver i;
if (method.compareTo("Heun") == 0) {
i = new Heun(this);
}
else if (method.compareTo("Euler") == 0) {
i = new Euler(this);
+ " n=" + n
CHAPTER 6. ANSWERS CHAPTER 6
66
}
else if (method.compareTo("RK") == 0) {
i = new RK(this);
}
else {
i = new Heun(this);
}
return i;
}
}
class f2 implements Func {
public double f (double x) {
// return Math.exp(-x*x)*Math.log(1+x*Math.sin(x)); }
// return 2*x; }
return 1+4*x; }
}
class P62 {
public static void main (String argv[])
{
ODESolver_prm p = new ODESolver_prm();
p.read(argv);
p.write();
f2 f = new f2();
ODESolver i = p.create();
double result [];
result = i.calculate();
System.out.println(result[p.n]);
}
}
C++ classes for Project 6.7.2
class ODEProblem
{
protected:
ODESolver*
solver;
// some ODE solver
MyArray<double> y, y0;
// solution (y) and initial condition (y0)
double
t, dt, T; // time loop parameters
public:
ODEProblem () {}
virtual ˜ODEProblem ();
virtual void timeLoop ();
virtual void equation (MyArray<double>& f,
const MyArray<double>& y, double t);
virtual int size (); // no of equations in the ODE system
virtual void scan ();
virtual void print (ostream& os);
};
67
void ODEProblem:: timeLoop ()
{
ofstream outfile("y.out");
t = 0; y = y0;
outfile << t << " "; y.print(outfile); outfile << endl;
while (t <= T) {
solver->advance (y, t, dt);
outfile << t << " "; y.print(outfile); outfile << endl;
}
}
void ODEProblem:: scan ()
{
const int n = size(); // call size in actual subclass
y.redim(n); y0.redim(n);
cout << "Give " << n << " initial conditions: ";
int i;
for(i=1; (i<=n) && (cin>>y0(i)); i++);
cout << "Read " << i-1 << "elements";
y0.print(cout); cout<<endl;
// y0.scan(cin);
cout << "Give time step: ";
cin >> dt;
cout << "Give final time T: "; cin >> T;
ODESolver_prm solver_prm;
cout << "Give name of ODE solver: ";
cin >> solver_prm.method;
solver_prm.problem = this;
solver = solver_prm.create();
solver->init();
// more reading in user’s subclass
}
void ODEProblem:: print (ostream& os)
{
os << "\n\n\tIntegrating ODE system\n"
<< "\tTime interval: [" << 0.0 << "," << T << "]\n"
<< "\tInitial condition: y0= (";
y0.print(os); os << ")\n";
}
void ODEProblem:: equation
(MyArray<double>& /*f*/, const MyArray<double>& /*y*/, double /*t*/)
{
cout << "\n\nODEProblem::equation:\n\t"
<< "This function must be implemented in a subclass!\n\n";
}
68
CHAPTER 6. ANSWERS CHAPTER 6
int ODEProblem:: size ()
{
cout << "\n\nODEProblem::size:\n\t"
<< "This function must be implemented in a subclass!\n\n";
return 0;
}
ODEProblem:: ˜ODEProblem ()
{
// solver is created in scan, by createODESolver:
delete solver;
}
class ODESolver_prm
{
public:
char
method[30];
ODEProblem* problem;
ODESolver*
create ();
};
// name of subclass in ODESolver hierarchy
// pointer to user’s problem class
// create correct subclass of ODESolver
ODESolver* ODESolver_prm::create ()
{
ODESolver* ptr = NULL;
if
(strcmp(method, "ForwardEuler") == 0)
ptr = new ForwardEuler (problem);
else if (strcmp(method, "RungeKutta4") == 0)
ptr = new RungeKutta4 (problem);
else if (strcmp(method, "Heun4") == 0)
ptr = new Heun4 (problem);
else {
cout << "\n\nODESolver_prm::create:\n\t"
<< "Method " << method << " is not available\n\\n";
exit(1);
}
return ptr;
}
class ODESolver
{
protected:
// members only visible in subclasses
ODEProblem* eqdef;
// definition of the ODE in user’s class
public:
// members visible also outside the class
ODESolver (ODEProblem* eqdef_)
{ eqdef = eqdef_; }
virtual ˜ODESolver () {} // always needed, does nothing here...
virtual void init() {}
// initialize solver data structures
virtual void advance (MyArray<double>& y, double& t, double& dt);
};
69
void ODESolver::advance(MyArray<double>& /*y*/,
double& /*t*/, double& /*dt*/)
{
cout << "\n\nODESolver::advance:\n\t"
<< "This function must be implemented in a subclass!\n\n";
}
class ForwardEuler : public ODESolver
{
MyArray<double> scratch1;
// needed in the algorithm
public:
ForwardEuler (ODEProblem* eqdef_);
virtual void init (); // for allocating scratch1
virtual void advance (MyArray<double>& y, double& t, double& dt);
};
ForwardEuler::ForwardEuler(ODEProblem* eqdef_) : ODESolver(eqdef_) {}
void ForwardEuler:: init ()
{
// allocate internal data structure:
scratch1.redim (eqdef->size());
}
void ForwardEuler::advance(MyArray<double>& y, double& t, double& dt)
{
eqdef->equation (scratch1, y, t); // evaluate scratch1 (as f)
const int n = y.size();
for (int i = 1; i <= n; i++)
y(i) += dt * scratch1(i);
t += dt;
}
class RungeKutta4 : public ODESolver
{
MyArray<double> scratch1, scratch2, scratch3; // needed in algorithm
public:
RungeKutta4 (ODEProblem* eqdef_);
virtual void init ();
virtual void advance (MyArray<double>& y, double& t, double& dt);
};
RungeKutta4::RungeKutta4(ODEProblem* eqdef_) : ODESolver (eqdef_) {}
void RungeKutta4:: init ()
{
// allocate internal data structure:
const int n = eqdef->size();
scratch1.redim (n); scratch2.redim (n); scratch3.redim (n);
}
void RungeKutta4:: advance (MyArray<double>& y, double& t, double& dt)
70
CHAPTER 6. ANSWERS CHAPTER 6
{
const double dt2 = 0.5*dt;
const double dt6 = dt/6.0;
const int n = y.size();
eqdef->equation (scratch1, y, t);
int i;
for (i = 1; i <= n; i++)
scratch2(i) = y(i) + dt2 * scratch1(i);
eqdef->equation (scratch1, scratch2, t+dt2);
for (i = 1; i <= n; i++)
scratch2(i) = y(i) + dt2 * scratch1(i);
eqdef->equation (scratch3, scratch2, t+dt2);
for (i = 1; i <= n; i++)
{
scratch2(i) = y(i)
+ dt * scratch3(i);
scratch3(i) = scratch1(i) + scratch3(i);
}
eqdef->equation (scratch1, scratch2, t+dt);
eqdef->equation (scratch2, y, t);
for (i = 1; i <= n; i++)
y(i) = y(i) + dt6*(scratch1(i) + scratch2(i) + 2*scratch3(i));
t += dt;
}
class Heun : public ODESolver
{
MyArray<double> scratch1, scratch2, scratch3; // needed in algorithm
public:
Heun (ODEProblem* eqdef_);
virtual void init ();
virtual void advance (MyArray<double>& y, double& t, double& dt);
};
Heun::Heun(ODEProblem* eqdef_) : ODESolver (eqdef_) {}
void Heun:: init ()
{
// allocate internal data structure:
const int n = eqdef->size();
scratch1.redim (n); scratch2.redim (n); scratch3.redim (n);
}
void Heun:: advance (MyArray<double>& y, double& t, double& dt)
{
const double dt2 = 0.5*dt;
const int n = y.size();
eqdef->equation (scratch1, y, t);
int i;
for (i = 1; i <= n; i++)
scratch2(i) = y(i) + dt *scratch1(i);
71
eqdef->equation (scratch3, scratch2, t);
for (i = 1; i <= n; i++)
y(i) = y(i) + dt2*(scratch1(i) + scratch3(i));
t += dt;
}
The MyArray template class, used in the C++ classes.
template <class T>
class MyArray
{
protected:
T*
A;
int
length;
void
allocate (int n);
void
deallocate();
public:
MyArray ();
MyArray (int n);
MyArray (const MyArray<T>& w);
˜MyArray ();
// vector entries (C-array)
// allocate memory, length=n
// free memory
//
//
//
//
MyArray<T> v;
MyArray<T> v(n);
MyArray<T> v(w);
clean up dynamic memory
int redim (int n);
int size () const { return length; }
// v.redim(m);
// n = v.size();
void operator= (const MyArray<T>& w);
T operator() (int i) const;
T& operator() (int i);
// v = w;
// a = v(i);
// v(i) = a;
void print (ostream& o) const;
};
template<class T>
void MyArray<T>::allocate(int n)
{
length = n;
A = new T[n];
}
// v.print(cout);
template<class T>
void MyArray<T>::deallocate()
{
delete [] A;
length = 0;
}
template<class T> MyArray<T>::MyArray()
{ A = NULL; length=0; }
template<class T> MyArray<T>::MyArray(int n)
72
CHAPTER 6. ANSWERS CHAPTER 6
{ allocate(n); }
template<class T> MyArray<T>::MyArray(const MyArray<T>& w)
{
allocate(w.size());
*this = w;
};
template<class T> MyArray<T>::˜MyArray()
{ deallocate(); }
template<class T>
int MyArray<T>::redim(int n)
{
if (length==n)
return 0;
if (A!= NULL)
deallocate();
allocate(n);
return 1;
};
template<class T>
void MyArray<T>::operator=(const MyArray<T> & w)
{
redim (w.size());
for (int i=0; i<length; i++)
A[i] = w.A[i];
}
template<class T>
inline T MyArray<T>::operator()(int i) const
{
#ifdef SAFETY_CHECKS
if (i < 1 || i > length)
cout << "MyArray::operator(), illegal index, i=" << i;
#endif
return A[i-1];
}
template<class T>
inline T& MyArray<T>::operator()(int i)
{
#ifdef SAFETY_CHECKS
if (i < 1 || i > length)
cout << "MyArray::operator(), illegal index, i=" << i;
#endif
return A[i-1];
}
73
template<class T>
inline ostream& operator<< (ostream& o, const MyArray<T>& v)
{ v.print(o); return o; }
template<class T>
void MyArray<T>::print(ostream& o) const
{
for (int i=1; i<=length; i++)
o << (*this)(i) << ((i==length) ? "" : " ");
}
A sample problem, for testing the C++ program.
class Simprob : public ODEProblem
{
protected:
double c1,c2,c3,c4,omega; // problem dependent paramters
public:
Simprob () {}
virtual void equation (MyArray<double>& f,
const MyArray<double>& y, double t);
virtual int size () { return 1; } // 2x2 system of ODEs
virtual void scan ();
virtual void print (ostream& os);
};
void Simprob::equation(MyArray<double>& f,
const MyArray<double>& y, double t)
{
f(1) = c1+c2*y(1);
}
void Simprob:: scan ()
{
// first we need to do everything that ODEProblem::scan does:
ODEProblem::scan();
// additional reading here:
cout << "Give c1, c2: ";
cin >> c1 >> c2;
print(cout); // convenient check for the user
}
void Simprob:: print (ostream& os)
{
// print everything that ODEProblem::print prints:
ODEProblem::print(os);
// print the equation:
os << "The equation solved by class Simprob reads\n"
CHAPTER 6. ANSWERS CHAPTER 6
74
<< "dy/dt = " << c1 << " + "<< c2<<"*y\n";
}
int main (int argc, const char* argv[])
{
Simprob problem;
problem.scan();
// read input data and initialize
problem.timeLoop(); // solve problem
}
ODEs.py
import sys
from Numeric import *
class ODEs:
"""
Base class for numerical methods for ODEs.
"""
def __init__(self, p):
self.prm = p # ODEs_prm object
def calculate(self):
"""Perform integration."""
# to be implemented in subclasses
return "ODEs.calculate; not impl. in subclass"
class Heun(ODEs):
"""
Heun’s method, 2. order Runge-Kutta.
"""
def __init__(self, p):
ODEs.__init__(self, p)
def calculate(self):
p = self.prm; f = p.f; g = p.g; n = p.npoints; y0 = p.y0; z0 = p.z0
u = zeros(n+1, Float)
y=y0 #initial conditions
z=z0
# advance n steps:
for i in range (0,n,1):
v = f(y,z)
w = g(y,z)
y2 = y +Dt*0.5*(v + f(y+Dt*v,z+Dt*w))
z2 = z +Dt*0.5*(w + g(y+Dt*v,z+Dt*w))
y=y2
75
z=z2
return (y,z)
class ODEs_prm:
"""
Holds all parameters needet to initiate objects
in the ODEs hierarcy.
"""
def __init__(self):
self.default()
return
def default(self):
"""assign appropriate default values to all parameters"""
self.tstop = 1
self.y0 = 1
self.z0 = 1
self.dt = 0.01
self.f = Function(’y+z’, independent_variable=’y’,\
independent_variable2=’z’)
self.g = Function(’y-z’, independent_variable=’y’,\
independent_variable2=’z’)
self.method = "Heun"
self.npoints = int(self.tstop/self.dt)
def read(self, argv=sys.argv[1:]):
# manual parsing
for i in range(0,len(argv),2):
if argv[i] == "-s": self.tstop = float(argv[i+1])
if argv[i] == "-d": self.dt = float(argv[i+1])
if argv[i] == "-f": self.f = Function(argv[i+1])
if argv[i] == "-g": self.g = Function(argv[i+1])
if argv[i] == "-m": self.method = argv[i+1]
if argv[i] == "-y": self.y0 = float(argv[i+1])
if argv[i] == "-z": self.z0 = float(argv[i+1])
self.npoints = int(self.tstop/self.dt)
def write(self):
print "Dt=%g tstop=%g npoints=%g y0=%g z0=%g f=’%s’ g=’%s’ \
method=%s" % \
(self.dt, self.tstop, self.npoints, self.y0, self.z0, \
self.f.__name__, self.g.__name__, self.method)
def create(self):
"""Create subclass of ODE"""
code = "i = %s(self)" % self.method
exec(code) # turn string into Python code
return i
class Function:
CHAPTER 6. ANSWERS CHAPTER 6
76
"""
Unified treatment of functions; strings or function objects.
Examples on usage:
def myfunc(x,y):
return x+y
f = Function(myfunc, ’x’,’y’)
v = f(2,1)
print v
# attach Python function
f = Function(’1+x-2*y’, ’x’, ’y’)
v = f(1,2)
print v
"""
# specify function by string
def __init__(self, f, independent_variable=’u’,\
independent_variable2=’v’):
self.f = f # expression or function object
self.var = independent_variable # ’x’, ’t’ etc.
self.var2 =independent_variable2 # ’x’, ’t’ etc.
if type(f) == type(""):
self.f_is_string = 1
self.__name__ = self.f
else:
# function object:
self.f_is_string = 0
self.__name__ = self.f.__name__
def __call__(self, u, h):
if self.f_is_string:
exec("%s = %g" % (self.var, u))
exec("%s = %g" % (self.var2, h))
return eval(self.f)
else:
return self.f(u,h)
p63.py
#!/usr/bin/env python
from ODEs import *
# give access to library
from math import *
from sys import *
o=ODEs_prm()
o.read(sys.argv[1:])
o.write()
i=o.create()
result = i.calculate()
print result
Chapter 7
Answers Chapter 7
Exercises
7.1
In this model we think of the drop of ink as being 2∆x long when we inject it, and
the time the injection itself takes is 2∆t. This results in the source function as given.
Assuming the tube is sealed at the ends, the PDE becomes
∂u
∂t
u(x, 0)
∂u
∂x
=
∂2u
+ f (x, t),
∂x2
0,
=
0 for x = 0, L.
= k
The concentration of ink will increase with time. It will be strongest in the middle of
the tube (L/2) and weaker towards the edges.
7.2
This temperature problem could e.g. represent a pipe buried vertically in the ground.
In this case the lower end would be at constant temperature, while the top end would
be exposed to a day-night cycle.
7.3
This could e.g. be a description of the flow of lubrication between two surfaces in a
machine.
7.4
Replace the physical variables u, t, and x with the dimensionless variables ū, t̄ and x̄.
ū =
L2
t
x
u
, tc =
, t̄ = , x̄ =
c0
k
tc
L
Note that
77
CHAPTER 7. ANSWERS CHAPTER 7
78
∂u ∂ t̄
∂ t̄ ∂u
1 ∂
c0 ∂ ū
∂u
=
=
=
ūc0 =
,
∂t
∂ t̄ ∂t
∂t ∂ t̄
tc ∂ t̄
tc ∂ t̄
and;
∂
∂2u
=
∂x2
∂x
∂ x̄ ∂u
∂x ∂ x̄
∂ 1
=
∂ x̄ L
1 ∂
ūc0
L ∂ + x̄
=
c0 ∂ 2 ū
.
L2 ∂ x̄2
The source term becomes
L2
A sin2 ω t̄
exp(−L2 (x̄ − x¯0 )2 ).
k
Dropping the bars, we can now write the PDE as
2
∂u
l
∂ 2 u AL2
2
exp(−L2 (x̄ − x¯0 )2 ).
ω t̄
+
=
sin
∂t
∂x2
kc0
k
7.5
The discrete version of the Robin boundary conditions can be written as
for x = 0 :
for x = 1 :
ul2 − ul0
= α(ul1 − us ),
2∆x
uln+1 − uln−1
= α(uln − us ).
2∆x
−
These equations contain the values ul0 and uln+1 , both of which are outside the grid.
However, we can combine the equations above with the scheme (7.81) itself, which for
(x = 0) reads:
ul+1
= ul1 +
1
∆t l
(u − 2ul1 + ul2 ) + ∆tf1l
∆x2 0
We now have two equations involving ul0 and can eliminate it, resulting in the equation
ul+1
= ul1 + 2
1
∆t
(∆xα − 1)ul1 − ∆xαus + ul2 + ∆tf1l .
2
∆x
Using the same method for (x = 1) results in
ul+1
= uln + 2
n
∆t
(∆xα − 1)uln − ∆xαus + uln−1 + ∆tfnl .
2
∆x
7.6
See the program ex76.py.
79
7.7
u(x, t)
∂u
∂t
∂u
∂x
∂2u
∂x2
2
= e−π t cos(πx)
2
= −π 2 e−π t cos(πx)
2
= e−π t π(− sin(πx))
2
= e−π t ππ(− cos(πx))
(7.91) satisfies ut = uxx .
∂
u(0, t)
∂x
∂
u(1, t)
∂x
2
= e−π t π(− sin(0)) = 0
2
= e−π t π(− sin(π)) = 0
(7.91) satisfies Neumann boundary conditions. This solution is used in the program
ex76.py.
7.8
In order to prove that u(x, t) is a solution to the diffusion equation we simply observe
that
∂
u(x, t)
∂t
∂2
u(x, t)
∂x2
= −ae−at sin(b(x − c))
= −b2 e−at sin(b(x − c))
Note that a = b2 . The function u can be made to fit certain Dirichlet boundary conditions on the form g0 (t) = αe−βt by choosing a = β, and c so that sin(−bc) = α.
For g1 (t) = αe−βt this instead becomes sin(b(1 − c)) = α. Similarly, for Neumann conditions of the same form, c must be choosen so that b cos(−bc) = α, or
(for x = 1) b cos(b(1 − c)) = α. In order to verify Algorithm 7.4 we simply choose
a set of values for a, b, and c, and run the algorithm with u(x, 0) = sin(b(x − c)),
g0 (t) = exp(−at) sin(−bc), and g1 (t) = exp(−at) sin(b(1 − c)). The results of the
numerical calculation should now be the same as the equation u(x, t).
7.9
An exact solution of the problem is
u(x, t) = e−
π2
4
t
π
sin( (x − 1)),
2
when the initial values are set to be I(x) = sin π2 (x − 1)).
CHAPTER 7. ANSWERS CHAPTER 7
80
7.10
Look at the derivatives of û:
û(x, t)
∂ û
∂t
∂ 2 û
∂x2
= av(x, t) + bw(x, t)
∂v
∂w
= a
+b
∂t
∂t
∂2v
∂w2
= a 2 +b 2
∂x
∂x
As both v and w solves the diffusion PDE we know that vt = vxx and wt = wxx , and
so
ût = avt + bwt = avxx + bwxx = ûxx .
The boundary and initial conditions for û are simply
û(0, t)
= av(0, t) + bw(0, t),
û(1, t)
û(x, 0)
= av(1, t) + bw(1, t),
= av(x, 0) + bw(x, 0).
Now let us look at the function u(x, t; k)
u(x, t; k)
∂u
∂t
∂2u
∂x2
= e−π
2 2
k t
sin(πkx),
= −π 2 k 2 e−π
= e−π
2 2
k t
2 2
k t
sin(πkx),
πkπk(− sin(πkx)).
We see that ut = uxx and so u is also a solution of the diffusion PDE without source
terms. The boundary and initial conditions for û(x, t) = u(x, t; 1) + u(x, t; 100) are
û(0, t)
û(1, t)
=
=
0,
0,
û(x, 0)
=
sin(πx) + 0.1 sin(100πx).
The time t = T when there is no visible track of w(x, t) will depend on the program
used for plotting.
2 2
When t or k are lage, e−π k t is small, and u(x, t, k) is small. Since k is larger in w,
this part vanishes faster than u.
7.11
The finite difference scheme is
ul − 2uli + uli+1
− uli
ul+1
i
= i−1
.
∆t
∆x2
81
Inserting (7.93) results in
A
h
1−
4∆t
∆x2
A 1−
sin2
4∆t
∆x2
πk∆x
2
sin2
l+1
πk∆x
2
− 1−
l
4∆t
∆x2
sin2
πk∆x
2
∆t
l i
sin(πk(i − 1)∆x)
=
[sin(πk(i − 2)∆x) − 2 sin(πk(i − 1)∆x) + sin(πki∆x)]
,
∆x2
which can be reduced to
− 1 sin(πk(i − 1)∆x)
=
∆t
[sin(πk(i − 2)∆x) − 2 sin(πk(i − 1)∆x) + sin(πki∆x)]
.
∆x2
1−
4∆t
δx2
sin2
πk∆x
2
This, using a few trigonometric formulas, becomes
2 cos2 (πk∆x) [sin (πki∆x) cos (πk∆x) − cos (πki∆x) sin (πk∆x)] =
sin (πki∆x) cos (πk2∆x) − cos (πki∆x) sin (πk2∆x) + sin (πki∆x) ,
which in turn becomes
cos2 (πk∆x) = 1 − sin2 (πk∆x) .
The boundary conditions are
l
πk∆x
4∆t
sin(πk(1 − 1)∆x) = 0,
ul1 = A 1 − 2 sin2
δx
2
and
l
πk∆x
4∆t
sin(πk) = 0.
uln = A 1 − 2 sin2
δx
2
The initial condition is
u0i = A sin(πk(i − 1)∆x).
7.12
Taylor expansion of ey and sin2 y:
ey
sin2 y
=
1+y+
= y2 +
y2
y3
+
+ O(y 4 )
2
6
y4
+ O(y 6 )
3
Now we replace the relevant parts of the function for e(k, ∆x, ∆t) with the two first
terms in their power series expansion:
CHAPTER 7. ANSWERS CHAPTER 7
82
e(k, ∆x, ∆t)
4∆t
πk∆x
sin2
∆x2 2
4∆t π 2 k 2 ∆x2
π 4 k 4 ∆x4
2 2
≈ 1 − π k ∆t − 1 +
+
∆x2
4
48
4 4
2
∆tπ k ∆x
=
12
= e−π
2 2
k ∆t
−1+
The leading term in the expansion of e is proportional to ∆t and ∆x2 .
7.13
In equation (7.93) uli may increase with time if
1 − 4∆t sin2 πk∆x ∆x2
2
is greater than one. The only way for this to happen is to have
πk∆x
4∆t
2
> 2,
sin
∆x2
2
which only happens when
1
∆x2 .
2
In this case the numerical solution is unstable.
∆t >
7.14
Algorithm for solving (7.72)
SET INITIAL CONDITIONS:
u0i = I(xi ), for i = 1, . . . , n
for l = 0, 1, . . . , m
UPDATE ALL INNER
POINTS
ul
−ul
∆t
i
− ki− 21
ki+ 12 i+1
ul+1
= uli + γ1i ∆x
i
∆x
for i = 2, . . . , n − 1
INSERT BOUNDARY CONDITIONS
ul+1
= ul1 +
1
= uln +
ul+1
n
l
uli −uli−1
∆x
+
∆t l
γi fi
l
1 ∆t(u2 −u1 )
l
(k3/2 + k1/2 ) + ∆t
γi
∆x2
γi f1
l
l
1 ∆t(un−1 −un )
(kn+1/2 + kn−1/2 )
γi
∆x2
Projects
7.4.1; Diffusion of a jump
a)
̺cv
∂u
∂t
= k
∂2u
,
∂x2
+
∆t l
γi fn
83
Figure 7.1: Project 7.1. Two pieces of metal with different temperature are brought
together.
∂u
∂x
=
u(0, t)
=
−k
0,
for x = 0, 2L,
U1 ,
U2 ,
x≤L
.
x>L
(NOTE: It is assumed that the pieces are of the same length L and are made of the
same metal.)
b) Scaling the problem, using
ū =
u − U1
,
U1 − U2
and assuming U1 < U2 results in the equations
∂u
∂t
∂u
∂x
u(0, t)
=
=
=
c) See program p71.m, and Figure 7.1.
d) In order to show that
∂ 2 us
,
∂x2
0,
for x = 0, 1,
0,
1,
x ≤ 0.5
.
x > 0.5
CHAPTER 7. ANSWERS CHAPTER 7
84
maximum error
0.1
0.05
0
0
0.1
0.2
0.3
0.4
0.5
time
0.6
0.7
0.8
0.9
1
0.5
u
Numerical approximation
Exact solution
0
t=0.1
−0.5
0
0.1
0.2
0.3
0.4
0.5
x
0.6
0.7
0.8
0.9
1
Figure 7.2: Project 7.1 d. Comparing the exact solution to the results of the numerical
approximat, when the initial condition is u(0, x) = cos(πx).
2
u(x, t) = e−π t cos(πx)
is a solution, simply insert u(x, t) in the equations for the scaled problem:
∂u
∂t
∂2u
∂x2
∂
u(0, t)
∂x
∂
u(1, t)
∂x
2
= −π 2 e−π t cos(πx),
2
= −π 2 e−π t cos(πx),
2
= −πe−π t sin(0) = 0,
=
2
0 − πe−π t sin(π) = 0.
Plotting both this exact solution and the approximation yielded by the numerical
method (Figure 7.2) shows that the error in the numerical results decreases with
time. This indicates that the code is free of bugs.
e) We know from experience (and thermodynamics) that if we place two items of
different temperatures in contact, heat will flow from the warm item to the cold
one. In the simple case of two equally big pieces of the same metal the temperature
of both pieces will eventually become the average of the two starting temperatures.
This is consistent with the result shown in Figure 7.1, where the temperature of
both pieces becomes T = 0.5.
85
f) In this problem the solution will reach a stationary solution just after T = 3. The
exact time will vary depending on ∆t and ∆x.
g) We have solved this problem (at least approximately) in exercise f, for the scaled
time, t̄. In order to find the time as a function of heat conduction and total lenght of
the pieces, we simply use t = t̄tc where t̄ = 3, and
tc =
1
̺cv 4L2 .
k
7.4.2; Periodical Injection of Pollution
a) The source term f can be specified as
f (x, t) =
K, r ≤ r0 , i ≤ t ≤ i + 1/3, i = 1, 2, . . .
0, otherwise
where i is time in days, (eight hours is 1/3 day). This is implemented in the program
p72.m.
b) Complete initial-boundary value problem:
∂
∂
1 ∂
r2 c(r, t) + f (r, t),
c(r, t) = k 2
∂t
r ∂r
∂r
∂c
= 0 for r = 0,
∂r
c(t, r) = 0 for r = L,
c(0, r) = 0.
c) Finite difference scheme for (7.97):
∆r 2
∆r 2
k ∆t
l
(r
+
)
(c
−
c
)
−
(r
−
)
(c
−
c
)
+ ∆tfil
cl+1
=
c
+
i
i+1
i
i
i
i−1
i
i
ri2 ∆r2
2
2
Algorithm for solving (7.97)
SET INITIAL CONDITIONS:
c0i = 0, for i = 1, . . . , n
for l = 0, 1, . . . , m
UPDATE ALL INNER POINTS
∆t
2
(ri + ∆r
= cli + rk2 ∆r
cl+1
2
d)
i
2 ) (ci+1 − ci ) − (ri −
i
for i = 2, . . . , n − 1
INSERT BOUNDARY CONDITIONS:
cl+1
= cl1
1
cl+1
=
0
n
e) See the program p72.m.
∆r 2
2 ) (ci
− ci−1 ) + ∆tfil
CHAPTER 7. ANSWERS CHAPTER 7
86
f) A very simple test of the implementation would be to set K = 0 and confirm that
the concentration renmain zero throughout the simulation. For a more advanced test
one could calculate the total pollution present at all times and compare this with the
total pollution from the source term.
g) Scaling equation (7.97):
∂
∂ ∂ t̄
c0 ∂c̄
c=
c̄c0 =
∂t
∂ t̄ ∂t
tc ∂ t̄
1 ∂
k 2
r ∂r
1 1 ∂
c0 ∂
2 ∂
2 2 1 ∂
2 ∂
r
r̄ r0
r̄
c =k 2 2
c0 c̄ = k 2 2
c̄
∂r
r̄ r0 r0 ∂ r̄
r0 ∂ r̄
r̄ r0 ∂ r̄
∂ r̄
The complete equation now becomes
c0 ∂c̄
c0 ∂
=k 2 2
tc ∂ t̄
r̄ r0 ∂ r̄
∂
r̄
c̄ + K f¯.
∂ r̄
2
Using tc = r02 /k, and removing the bars this becomes
1 ∂
∂c
= 2
∂t
r ∂r
∂
r
c + αf,
∂r
2
where α = r0 K/kc0 . If we choose tc K as the scale for concentration α equals
unity.
h) The ideal value for L will vary with the induvidual users accuracy requirements.
We have used L = 20r0 .
i) The printed page is unsuited as a medium for animations, see instead figure 7.3 for
a look at how the concentration developes in time.
7.4.3; Compare different scalings
a) See the program p73.m. By running this program with different scalings and values
of β we see that scaling 1 fails when β ≫ 1 and scale 2 fails when β ≪ 1. (In this
context failing means that the values for u stray far from the values between zero
and one where we prefer to work. )
b) See figure 7.4.
c) The stationary solution, us , obviously does not change with time, and we have
determined in exercise c that the initial condition have no influence. The equations
determining us are:
∂ 2 us
∂x2
us (a)
∂us
k
∂x
k
=
0
= Ua
= Qb
for x = 2L
87
t=3.20
0.25
0.2
0.2
concentration
concentration
t=3.10
0.25
0.15
0.1
0.05
0
0.15
0.1
0.05
0
2
4
6
8
0
10
0
2
4
r
8
10
6
8
10
t=3.40
0.25
0.2
0.2
concentration
concentration
t=3.30
0.25
0.15
0.1
0.05
0
6
r
0.15
0.1
0.05
0
2
4
6
8
0
10
0
2
r
4
r
Figure 7.3: Project 7.2. Concentration of pollution by distance from the factory pipe.
In the three first figures the factory is active, and pollution is being injected. In the last
figure (t = 3.40) the factory is closed for the day.
1
Step initial condition
0.8
u
0.6
0.4
0.2
0
0
0.1
0.2
0.3
0.4
0.5
x
0.6
0.7
0.8
0.9
1
0.3
0.4
0.5
x
0.6
0.7
0.8
0.9
1
1
Initial condition: u=Ua
0.8
u
0.6
0.4
0.2
0
0
0.1
0.2
Figure 7.4: Project 7.4.3: The solutions after a certain time are the same, irrespective
of initial conditions. (β = 1)
CHAPTER 7. ANSWERS CHAPTER 7
88
Scaled versions:
Scale 1, ū =
u−Ua
Ub −Ua :
∂ 2 us
∂x2
us (a)
∂us
∂x
where β =
=
0
=
0
= β
for x = 1
Qb L
k(Ub −Ua ) .
Scale 2, ū =
k(u−Ua )
Qb (b−a) :
∂ 2 us
∂x2
us (a)
∂us
∂x
=
0
= Ua
=
1
for x = 1
2
∂
d) The time derivative of us is 0, which means that ∂x
2 us is zero. (i.e. us is a straight
line.) We can find the stationary solution by integrating twice:
u′s (x)
=
Z
u′′s (x)
dx =
Z
0 dx = C1
In the case of scale 1 we know that u′′ (x) = β at x = 1, which implies that C1 = β.
Z
Z
us (x) = u′s (x) dx = β dx = βx + C2
We know that us (x) = 0 at x = 0, i.e. C2 = 0. The stationary solution is simply
us (x) = βx. If β is much greater than unity then so is us . For scaling 2 the
stationary solution is simply us (x) = x.
Programs (Python, matlab)
ex76.py
#!/usr/bin/env python
# The diffusion equation with Neumann boundary conditions.
# Compares the results with the exact solution from exercise 7.7.
from Numeric import *
def diffeq(I, f, g0, g1, dx, dt, m, action=None):
n = int(1/dx + 1)
h = dt/(dx*dx)
x = arrayrange(0, 1+dx/2, dx, Float)
89
user_data= []
um = I(x)
u = zeros(n, Float)
for l in range(m+1):
t = l*dt
# Update all inner points
for i in range(1,n-1,1):
u[i] = um[i] + h*(um[i-1] - 2*um[i] + um[i+1]) + dt*f(x[i], t)
# Neumann boundary conditions:
u[0] = um[0] + (2*dt/(dx*dx))*(um[1] -um[0])
u[n-1] = um[n-1] + (2*dt/(dx*dx))*(um[n-2] -um[n-1] )
for i in range(len(u)): um[i] = u[i]
if action is not None:
r= action(u, x, t)
if r is not None:
user_data.append(r)
return user_data
C =
def
def
def
def
def
1.2
f0(x,t):
IC_0(x):
IC_1(x):
g0_0(t):
g1_0(t):
return
return
return
return
return
0.0
zeros(len(x), Float) +C
cos(pi*x)
0.0
0.0
def const_u(u, x, t):
e=sum(u- exp(-pi*pi*t)*cos(pi*x))
return e
dx = 0.1; dt = dx*dx/2.0; m = int(0.5/dt)
e = diffeq(IC_1, f0, g0_0, g1_0, dx,dt, m, action=const_u)
print "errors at time levels: ", e
p71.m
function p71(Dx,Dt,ts)
% Solves the scaled problem from exercise 7.4.1c.
% Will stop either when there is no more change
% in the temperature or at ts.
% example: p71(0.02,0.0002,0.2)
x=0:Dx:1;
t=0:Dt:ts;
alpha=Dt/(Dx*Dx)
u=zeros(length(x),length(t));
90
CHAPTER 7. ANSWERS CHAPTER 7
% initial condition:
i=fix(length(x)/2)+1
u(i:length(x),1)=1;
% For exercise d, instead use:
% u(:,1) =cos(pi.*x)’;
l= 1; k=1;
while (any(k) ˜= 0 & l< length(t) )
for i=2:(length(x)-1)
u(i,l+1)=u(i,l) + alpha*( u(i-1,l)-2*u(i,l) +u(i+1,l));
end
% boundary conditions:
u(1,l+1)=u(1,l) + 2*alpha*( u(2,l)- u(1,l) );
u(length(x),l+1)=u(length(x),l) + 2*alpha*( u(length(x)-1,l) -u(length(x
l=l+1;
k=u(:,l) - u(:,l-1)
end
% Plotting
mesh(t(1:l),x,u(:,[1:l]));
xlabel(’time’);
ylabel(’length’);
zlabel(’temperature’);
p72.m
function p72(Dr,ts,L,K)
%
% Solves the scaled problem from project 7.2.
% Plots concentration by distance from factory pipe
% at time ts.
% example: p72(0.1,3,20,1)
Dt= Dr*Dr/4;
r=0:Dr:L;
t=0:Dt:ts;
% initial condition:
c=zeros(length(r),1);
% calculation:
for j=1:lenght(t)
for i=2:length(r)-1
c(i)=c(i)+Dt*...
( (r(i)+Dr/2)ˆ2*(c(i+1)-c(i))-(r(i)-Dr/2)ˆ2*(c(i)-c(i-1)) )/(Dr*r(i
Dt*source(j*Dt,i*Dr,K);
% boundary conditions:
c(1)=c(2);
c(length(r))=0;
end
91
end
% Plotting
plot(r,c);
xlabel(’r’);
ylabel(’concentration’);
function s=source(t,r,K)
if (rem(t,1) < 1/3 & r<1)
s=K;
else
s=0;
end
p73.m
function p73(Dx,Dt,ts,s,beta)
%
% The heat conduction problem from project 7.4.3.
% Scaled in two different ways.
% Will stop either when there is no more change
% in the temperature or at ts.
% example: p73(0.02,0.0002,0.2,1,1)
x=0:Dx:1;
t=0:Dt:ts;
alpha=Dt/(Dx*Dx);
u=zeros(length(x),length(t));
if s==1
% Scaling 1
% initial condition:
i=fix(length(x)/2)+1;
u(i:length(x),1)=1;
% u(:,1) =cos(pi.*x)’;
length(t)
l= 1; k=1;
while (k > 1e-6 & l< length(t) )
for i=2:(length(x)-1)
u(i,l+1)=u(i,l) + alpha*( u(i-1,l)-2*u(i,l) +u(i+1,l));
end
% boundary conditions:
u(1,l+1)=0;
u(length(x),l+1)=u(length(x),l) + 2*alpha*( u(length(x)-1,l) -u(length(x),l) +be
l=l+1;
k = max(abs(u(:,l) - u(:,l-1)) );
end
92
CHAPTER 7. ANSWERS CHAPTER 7
plot(x,u(:,l),’r--’);
xlabel(’x’); ylabel(’u’);
elseif s==2
% Scaling 2
% initial condition:
i=fix(length(x)/2)+1;
u(i:length(x),1)=1/beta;
l= 1; k=1;
while (k > 1e-6 & l< length(t) )
for i=2:(length(x)-1)
u(i,l+1)=u(i,l) + alpha*( u(i-1,l)-2*u(i,l) +u(i+1,l));
end
% boundary conditions:
u(1,l+1)=0;
u(length(x),l+1)=u(length(x),l) + 2*alpha*( u(length(x)-1,l) -u(length(x
l=l+1;
k = max(abs(u(:,l) - u(:,l-1)) );
end
plot(x,u(:,l),’b:’);
xlabel(’x’); ylabel(’u’);
end
Chapter 8
Answers Chapter 8
Exercises
8.1
a)
ut
ux
uxx
= −k 2 π 2 ce−k
2
π2 t
sin(kπx)
−k2 π 2 t
kπ cos(kπx)
−k2 π 2 t
kπkπ(− sin(kπx)) = ut
= ce
= ce
b)
u(0, t)
u(1, t)
c) u(x, 0) = ce−k
2
π2 0
= ce−k
2
π2 t
−k2 π 2 t
= ce
sin 0 = 0
sin(kπ) = 0
sin(kπx) = c sin(kπx)
8.2
a)
f (x) =
∞
X
2
(1 − cos(kπ)) sin(kπx)
kπ
k=1
b) See the program ex82.m, and Figure 8.1.
c)
u(x, t) =
∞
X
2 2
2
(1 − cos(kπ)) e−k π t sin(kπx)
kπ
k=1
d) See the program ex82d.m, and Figure 8.2.
93
CHAPTER 8. ANSWERS CHAPTER 8
94
Fourier series of f(x)=1
1.4
1.2
1
f
0.8
0.6
0.4
0.2
0
N=3
N=7
N=80
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
Figure 8.1: Exercise 8.2b. Plots of the Nth partial sum of theFourier series of f (x) = 1,
for three different values of N.
e) For initial condition f (x) = x:
f (x)
u(x, t)
=
=
∞
X
−2
k=1
∞
X
k=1
kπ
cos(kπ) sin(kπx)
2 2
−2
cos(kπ)e−k π t sin(kπx)
kπ
See the program ex82e.m, and Figure 8.3.
8.3
a)
ck =
−4(1 + 2 cos(kπ))
k3 π3
b)
u(x, t) =
∞
X
−4(1 + 2 cos(kπ))
k=1
c) Explicit scheme:
u0i
= x2i − x3i
k3 π3
e−k
2
π2 t
sin(kπx)
95
8d) N=3
0.12
t=0.25
t=2
0.1
u
0.08
0.06
0.04
0.02
0
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
Figure 8.2: Exercise 8.2d. Plots of the 3rd partial sum of the formal solution of exercise
c. The plots for N=7, N=80, and N=100 look exactly the same.
8e) N=7, t=0
1.2
1
u
0.8
0.6
0.4
0.2
0
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
Figure 8.3: Exercise 8.2e. Figure made with the program ex82e.m. This one shows the
7th partial sum at time 0, which is just the Fourier series of f (x). (Stapled line shows
f (x) = x.)
CHAPTER 8. ANSWERS CHAPTER 8
96
8.3 N=50, t=2
−10
4
x 10
Explicit scheme
Formal solution
3.5
3
f
2.5
2
1.5
1
0.5
0
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
Figure 8.4: Exercise 8.3. Two different approximations of the solution to (8.91)-(8.93)
at time 2: The explicit scheme, and the 50 first terms of the formal solution.
ul+1
i
=
= ul+1
ul+1
1
0
=
∆t l
(u
− 2uli + uli+1 ) + uli i = 2, . . . , n − 1
∆x2 i−1
0
d)+f) See the program ex83.m.
e)+g) See Figure 8.4.
8.4
a)
f (x) =
∞
X
2kπ (1 − e cos(kπ)) sin(kπx)
k=1
1 + k2 π2
b) See the program ex84.m.
c) See the program ex84c.m, and Figure 8.5.
8.5
Using (8.71):
Z
Z
Z 1
1 1
1 1
cos((k − l)πx) dx −
cos((k + l)πx) dx
sin(kπx) sin(lπx) dx =
2 0
2 0
0
97
N=10
3
x
e
Fourier series
2.5
f
2
1.5
1
0.5
0
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
Figure 8.5: Exercise 8.4. Plot of the 10th partial sum of the Fourier series for ex .
If k = l:
1
2
Z
1
cos((k − l)πx) dx −
0
1
2
Z
1
cos((k + l)πx) dx
=
1
2
=
1
2
0
Z
1
cos 0 dx −
0
Z
1
0
1
1 sin(2kπx)
2
2kπ
0
1
1
1 dx − [0 − 0] =
2
2
If k 6= l:
1
2
Z
1
0
1
cos((k − l)πx) dx −
2
Z
1
cos((k + l)πx) dx
=
0
=
1
1
1 sin((k − l)πx)
1 sin((k + l)πx)
−
2
(k − l)π
2
(k + l)π
0
0
1
1
[0 − 0] − [0 − 0] = 0
2
2
8.6
a) Using (8.71):
Z L
Z
Z
1 L
lπx
kπx
1 L
(k − l)πx
(k + l)πx
sin
sin
dx =
dx−
) dx
cos
cos
L
L
2
L
2
L
0
0
0
if k = l:
1
2
Z
0
L
cos
1
(k − l)πx
dx −
L
2
Z
0
L
cos
(k + l)πx
) dx
L
=
1
2
Z
0
L
cos 0 dx −
L
2kπx
1 L
sin
2 2kπ
L 0
CHAPTER 8. ANSWERS CHAPTER 8
98
1
2
=
Z
L
0
1
L
1 dx − [0 − 0] =
2
2
if k 6= l:
1
2
Z
L
0
=
=
Z
1
(k − l)πx
dx −
L
2
L
(k + l)πx
) dx
L
0
L
L
1
L
L
(k − l)πx
(k + l)πx
1
sin
sin
−
2 (k − l)π
L
2 (k + l)π
L
0
0
1
1
[0 − 0] − [0 − 0] = 0
2
2
cos
cos
b) We want to find the constants c1 , c2 , . . . such that:
∞
X
kπx
ck sin
f (x) =
for x ∈ (0, L)
L
k=1
Multipy the left and right side of the equation by sin(lπx/L) and integrate:
Z
L
f (x) sin
0
lπx
L
dx =
Z
0
L
∞
X
ck sin
k=1
kπx
L
!
sin
lπx
L
dx
Interchange the order of integration and summation, and use the property from part
a:
Z L
Z L
∞
X
lπx
kπx
lπx
ck
dx =
sin
dx
sin
f (x) sin
L
L
L
0
0
k=1
=
L
cl
2
c)
ut
uxx
ut
kπx
ce
sin
= −
L
2
kπ
kπx
kπ
−( kπ
t
)
L
= ce
− sin
L
L
L
= uxx
kπ
L
2
2
−( kπ
L ) t
d)
∞
X
2kπ 1 − eL cos(kπ)
f (x) =
L2 + k 2 π 2
k=1
u(x, t) =
2 2
∞
X
2kπ(1 − eL cos(kπ) e−k π t
k=1
e)+f) See the program ex86.m.
L2 + k 2 π 2
L2
sin
kπx
L
99
8.7
a)-e) See the program ex87.m.
f)+g) See the program ex87g.m. This program can be altered to solve exercise f.
8.8
Use the property that
∂ −Kt
e
u(x, t)
∂t
= ut e−Kt − Kue−Kt
= uxx e−Kt − Kue−Kt .
This gives the result:
= uxx e−Kt − Kue−Kt + Kue−Kt
= uxx e−Kt = vxx
vt + Kv
Boundary conditions:
v(0, t)
= e−Kt u(0, t) = 0
v(1, t)
= e−Kt u(1, t) = 0
Initial condition:
v(x, 0) = e−K·0 u(x, 0) = u(x, 0) = f (x)
8.9
a) (8.85):
ul+1
i
= αuli−1 + (1 − 2α)uli + αuli+1
= G(uli−1 , uli , uli+1 )
b)
∂G
∂U−
∂G
∂U
∂G
∂U+
∆t
≥0
∆x2
1
= 1 − 2α ≥ 0 since α ≤
2
∆t
= α=
≥0
∆x2
= α=
c) The result from exercise b means that G(uli−1 , uli , uli+1 ) is never higher than G(ūlmax , ūlmax , ūlmax ).
= G(uli−1 , uli , uli+1 ) ≤ G(ūlmax , ūlmax , ūlmax ) = ūlmax
ul+1
i
l+1
As this inequality is true for all ul+1
i , it is true for ūmax .
CHAPTER 8. ANSWERS CHAPTER 8
100
d) Using induction on the above result gives ūlmax ≤ ū1max . For u1i the inner points
(i = 2, . . . , n − 1) must have a maximum smaller or equal to ū0max and the boundaries the value is known to be 0. This gives the result
ūlmax ≤ max max f (x), 0 .
x
e) The result from exercise b also indicate that G(uli−1 , uli , uli+1 ) is never lower than
G(ūlmin , ūlmin , ūlmin ).
= G(uli−1 , uli , uli+1 ) ≥ G(ūlmin , ūlmin , ūlmin ) = ūlmin
ul+1
i
l+1
This inequality is true for all ul+1
i , including ūmin . Using induction on this result
l
1
leads to ūmin ≥ ūmin . When Including the boundary conditions this leads to the
result
ūlmin ≥ min min f (x), 0 .
x
f) Equation (8.100) is a stronger result than equation (8.98) because we can derive
(8.98) from (8.100), but not the other way around. Equation (8.100) can be separated into three cases:
if f (x) > 0 ∀x
if f (x) < 0 ∀x
if max f (x) ≥ 0 ≥ min f (x)
then 0 ≤ uli ≤ max f (x)
then min f (x) ≤ uli ≤ 0
then min f (x) ≤ uli ≤ max f (x)
All three results in turn indicate that max |ui | ≤ max |f (x)| i.e. (8.100) implies
(8.98).
8.10
Z 1
∂
u2 (x, t) dx
∂t 0
Z 1
∂ 2
u (x, t) dx
=
∂t
0
Z 1
Z 1
2uuxx dx
2uut dx =
=
0
0
Z
= 2 u(1, t)ux (1, t) − u(0, t)ux (0, t) −
∂
E1 (t) =
∂t
= −2
Z
0
1
0
u2x dx ≤ 0
E ′ (t) ≤ 0 i.e. E1 (t2 ) ≤ E1 (t1 ) for all t2 ≥ t1 ≥ 0.
1
ux ux dx
101
8.11
For x ∈ (0, 1) and t < 0:
∂
∂
g(t) = f (x) = 0
∂t
∂t
∂
∂
f (x) =
g(t) = 0
∂x
∂x
Both f (x) and g(t) are constants. Since f (x) = g(t), they must be the same
constant.
8.12
Use the property that
Z
1
0
f (x) dx = F (1) − F (0) = 0,
where F ′ (x) = f (x). Because f (x) ≥ 0 in x ∈ (0, 1), F (x) is an increasing function.
In order to have F (1) = F (0), F ′ (x) (i.e. f (x)) must be zero for all x ∈ (0, 1).
8.13
a) WeRknow that f (x) ≥ 0, and that S is a subset of [0, 1]. This means that the sum
Rof f (x) dx on each interval that is part of S must be equal to or smaller than
f (x) dx on the entire interval [0, 1].
∞ Z
X
i=1
bi
ai
f (x) dx ≤
Z
1
0
f (x) dx ≤ ǫ
On each interval [ai , bi ] we have that
Z
bi
ai
√
f (x) dx ≥ (bi − ai ) min f (x) ≥ (bi − ai ) ǫ.
ai ≤x≤bi
Putting this together gives the result
Z 1
X 1 Z bi
√
1
√
f (x) dx ≤ ǫ,
f (x) dx ≤ √
(bi − ai ) ≤
|S| =
ǫ ai
ǫ 0
i=1
i=1
∞
X
which we wanted to prove.
2
b) u(x, t) = 8.1e−9π t sin(3πx)
2
c) v(x, t) = 8e−9π t sin(3πx)
d) 5 · 10−3
e) t = 10−4 : 4.96 · 10−3
t = 10−2 : 8.46 · 10−4
CHAPTER 8. ANSWERS CHAPTER 8
102
Projects
8.5.1; Neumann boundary conditions
a) Explicit scheme for solving (8.101)-(8.103) (using α = ∆t/∆x2 ):
ul+1
i
ul+1
1
unl+1
u0i
= uli + α(uli−1 − 2uli + uli+1 ) for i = 2, . . . , n − 1
2α(ul2 − ul1 ) + ul1
2α(uln−1 − uln ) + uln
=
=
= f (xi )
b) See the program p851.m.
c) (8.104) and (8.105) are approximations of the integrals from (8.7), using the composite trapezoid rule. For the inequality from (8.7) to be valid, the result of (8.104)
must be less than or equal to the result of (8.105). The table shows some results for
different ∆t and ∆x, for T = 1:
∆x
∆t
(8.104)
(8.105)
0.1
0.001
0.0776
0.0972
0.05
0.001
0.0776
0.0973
0.0002
0.0793
0.0973
0.02
0.02 0.000201 1.37 · 1036 0.0973
The results indicate that the inequality (8.7) is valid for the problem defined in
(8.101)-(8.103). The last result is an example of what can happen if α > 12 .
d) Multiply by u on both sides of equation (8.101), replace uut with
grate with respect to x:
Z
0
1
1 ∂ 2
u dx
2 ∂t
Z
=
1 ∂ 2
2 ∂t u ,
and inte-
1
uxx (x, t)u(x, t) dx
0
= ux (1, t)u(1, t) − ux (0, t)u(0, t) −
Z
1
ux (x, t)ux (x, t) dx
0
With the boundary conditions, ux (0, t) = ux (1, t) = 0, this becomes
1 ∂
2 ∂t
Z
1
0
u2 dx = −
Z
1
ux (x, t)ux (x, t) dx for t > 0.
0
This means that the time derivative of
Z
0
1
u2 (x, t) dx ≤
R1
0
Z
u2 dx is negative, i.e.
1
u2 (x, 0) dx for t > 0.
0
e) The two sums represent approximations of the integral from 0 to 1 of u and f .
By trying out different values of ∆x and ∆t we find that the two integrals are
approximately equal (as long as we remember to use ∆t ≤ ∆x2 /2).
103
f) The derivative of
∂
∂t
R1
u dx with respect to time is
0
Z
Z
1
u(x, t) dx
=
1
ut (x, t) dx
0
0
Z
=
1
uxx (x, t) dx
0
= ux (1, t) − ux (0, t) = 0 − 0 = 0.
This means that
R1
0
Z
u dx is constant in time, i.e.
1
u(x, t) dx =
Z
1
u(x, 0) dx =
1
f (x) dx.
0
0
0
Z
g) A simple numerical test of (8.106) is to have the program p851.m calculate the
difference between the maximum an minimum values of u. If the conjecture is
correct the difference will decrease as time increases. This experiment gives the
following results:
t
0
0.01
0.1
0.5
max(u) − min(u)
2
1.34
3.68 · 10−2
4.24 · 10−9
h) When u(x, t) = X(x)T (t) equation (8.101) becomes
X(x)T ′ (t) = X ′′ (x)T (t).
By dividing both sides by X(x)T (t) we get
T ′ (t)
X ′′ (x)
=
.
T (t)
X(x)
Now the left hand side depends only on t and the right hand side depends only on
x. This means both sides must be equal to a constant, which we can call λ, i.e.
T ′ (t)
X ′′ (x)
= λ,
= λ.
T (t)
X(x)
X(x)
=
X ′ (x)
=
X ′ (0)
=
X ′ (1)
=
u(x, t)
T (t)
1
ux (x, t)
T (t)
1
ux (0, t) = 0
T (t)
1
ux (1, t) = 0
T (t)
CHAPTER 8. ANSWERS CHAPTER 8
104
i) If T (t) = ceλt we get:
T ′ (t) =
∂ λt
ce = λceλt = λT (t)
∂t
j) If X(x) = cos(kπx) we get
X ′′ (x) =
∂2
cos(kπx) = −k 2 π 2 cos(kπx) = −k 2 π 2 X(x),
∂t2
which means that λ = −k 2 π 2 . We must also check the boundary conditions:
X ′ (0) = −kπ sin(0) = 0,
X ′ (1) = −kπ sin(kπ) = 0, for k = 0, 1, 2, . . .
2
2
k) We now know that u(x, t) = X(x)T (t) = e−k π t cos(kπx) is a solution of
(8.101) and (8.102). By the super-positioning principle any linear combination
of these solutions is also a solution. We can write the solutions as a series: (Using
cos(−y) = cos(y) and cos(0) = e0 = 1.)
∞
X
u(x, t) = c0 +
ck e−k
2
π2 t
cos(kπx)
k=1
l) If k = l = 0:
Z
1
cos(kπx) cos(lπx) dx
=
Z
1
cos(0)cos(0) dx
0
0
=
Z
1
12 dx = 1
0
If k = l > 0:
Z 1
cos(kπx) cos(lπx) dx
=
0
=
=
=
If k =
6 l:
Z 1
cos(kπx) cos(lπx) dx
=
0
=
=
1
2
Z
1
cos((k + l)πx) dx +
0
Z
1
cos((k − l)πx) dx
0
Z
1 1
cos(0) dx
2 0
0
1
Z
1 1
1 sin(2kπx)
+
1 dx
2
2kπ
2 0
0
1
2
1
2
1
2
Z
1
2
Z
0
1
cos(2kπx) dx +
1
cos((k + l)πx) dx +
1
2
Z
0
1
cos((k − l)πx) dx
1
1
1 sin((k − l)πx))
1 sin((k + l)πx))
+
2
(k + l)π
2
(k − l)π
0
0
0
105
m) If (8.109) holds then
c0
Z
= f (x) −
1
c0 dx
=
Z
1
c0
=
Z
Z
=
∞
1X
0 k=1
∞ Z 1
X
f (x) dx −
k=1 0
∞ X
1
ck
f (x) dx −
0
Z
Z
1
0
=
ck cos(kπx)
k=1
f (x) dx −
0
0
∞
X
k=1
1
ck cos(kπx) dx
ck cos(kπx) dx
sin(kπx))
kπ
1
0
f (x) dx.
0
Furthermore
f (x) cos(lπx) = c0 cos(lπx) +
Z
1
f (x) cos(lπx) dx
=
Z
∞
X
1
c0 cos(lπx) dx +
0
0
= c0
Z
1
cos(lπx) dx +
0
= c0
2
Z
ck cos(kπx) cos(lπx)
k=1
1
f (x) cos(lπx) dx
sin(2kπx)
2kπ
1
0
Z
∞
1X
0 k=1
Z 1X
∞
ck cos(kπx) cos(lπx) dx
ck cos(kπx) cos(lπx) dx
0 k=1
+ ck
1
2
= ck
0
n)
2
u(x, t) = 3.14 + e−4π t cos(2πx)
o)
2
lim u(x, t) = lim (3.14 + e−π t cos(2πx)) = 3.14
t→∞
1
Z 1
Z 1
1
3.14 + cos(2πx)dx = 3.14 +
f (y)dy =
sin(2πx) = 3.14
2π
0
0
0
t→∞
thus
lim u(x, t) =
t→∞
Z
0
1
f (y)dy ∀x ∈ [0, 1]
CHAPTER 8. ANSWERS CHAPTER 8
106
8.5.2; variable coefficients
a) Using the approximations (8.113)-(8.116), we generate a scheme for solving (8.110):
− uli
ul+1
i
∆t
ul+1
i
Where α =
(kux )(xi+1/2 , tl ) − (kux )(xi−1/2 , tl )
∆x
l
l
ki+1/2 (ui+1 − ui ) − ki−1/2 (uli − uli−1 )
=
∆x2
∆t
= uli +
ki+1/2 (uli+1 − uli ) − ki−1/2 (uli − uli−1 )
∆x2
= αki−1/2 uli−1 + (1 − α(ki+1/2 + ki−1/2 ))uli + αki+1/2 uli+1
=
∆t
∆x2 .
See program p852.m.
1
. This means that (1 − α(ki−1/2 +
b) We know that k ≤ M and that α ≤ 2M
ki+1/2 )) ≥ (1 − 2αM ) ≥ 0 and it follows from the triangle inequality that
|ul+1
i |
= |αki−1/2 uli−1 + (1 − α(ki−1/2 + ki+1/2 ))uli + αki+1/2 uli+1 |
≤
|αki−1/2 uli−1 | + |(1 − α(ki−1/2 + ki+1/2 ))uli | + |αki+1/2 uli+1 |
= αki−1/2 |uli−1 | + (1 − α(ki−1/2 + ki+1/2 ))|uli | + αki+1/2 |uli+1 |
≤ αki−1/2 ūl + (1 − α(ki−1/2 + ki+1/2 ))ūl + αki+1/2 ūl
= ūl
for i = 2, . . . , n − 1. Combined with the boundary conditions this means we can
write
ūl+1 ≤ ūl ,
and, using induction, we conclude that
max |uli | ≤ max |u0i | = max |f (xi )|.
i
i
i
c) (8.119) and (8.120) are approximations of the integrals from (8.7), using the composite trapezoid rule. For the inequality from (8.7) to be valid, the result of (8.119)
must be less than or equal to the result of (8.120). The results from program p852.m
indicate that the inequality is valid for this problem.
R1
d) We define E(t) = 0 u2 dx and
1 ∂
2 ∂t
Z
0
ut u
1
u2 (x, t) dx
=
(kux )x u
Z 1
(kux )x u dx
=
0
= k(1)ux (1, t)u(1, t) − k(0)ux (0, t)u(0, t) −
= −
Z
0
1
ku2x (x, t) dx
Z
0
1
ku2x (x, t) dx
107
Since both k(x) and u2x (x, t) are non-negative on x ∈ [0, 1] this means that E ′ (t) ≤
0, i.e.
Z
1
0
u2 (x, t) dx ≤
Z
1
u2 (x, 0) dx =
Z
1
f 2 (x) dx
0
0
e) We can test the bound by modifying the program p852.m so that it also calculates
a trapezoidal approximation of the two integrals in (8.121). Running the program a
few times with different values for ∆t and ∆x (mindful of the stability condition)
indicates that the bound (8.121) holds true.
f)
Z
0
1
u2t (x, t) dx
=
Z
1
(kux )x ut dx
0
= k(1)ux (1, t)ut (1, t) − k(0)ux (0, t)ut (0, t) −
= −
Z
1
Z
1
kux (x, t)uxt (x, t) dx
0
kux (x, t)uxt (x, t) dx
0
1 ∂
= −
2 ∂t
∂
∂t
Z
0
Z
1
0
ku2x (x, t) dx
1
ku2x (x, t) dx
= −2
Z
1
0
u2t (x, t) dx
the time derivative of the integral is always negative, leading to (8.121).
g) We have assumed that there exist numbers m and M such that 0 < m ≤ k(x) ≤
M , for x ∈ [0, 1]. We can use this to find the following bounds for the integral
expressions in (8.121).
Z
Z
1
0
1
0
k(x)u2x (x, t) dx
k(x)u2x (x, 0) dx
≥
≤
Z
1
mu2x (x, t) dx = m
0
Z
1
0
Z
1
u2x (x, t) dx
0
M u2x (x, 0) dx = M
Z
1
0
u2x (x, 0) dx
Combining this with expression (8.121) leads to
Z
0
1
u2x (x, t) dx ≤
M
m
Z
0
1
u2x (x, 0) dx =
M
m
Z
0
1
fx2 (x) dx
Programs (MATLAB)
ex82.m
function ex82(N)
% Plots the Nth partial sum of the Fourier series
108
CHAPTER 8. ANSWERS CHAPTER 8
% of f(x)=1, for x in (0,1).
% example: ex82(7)
x=0:0.02:1;
f=x.*0;
for k=1:N
c=2/(k*pi)*(1-cos(k*pi));
f=f+c*sin(x.*pi*k);
end
plot(x,f);
xlabel(’x’);
ylabel(’f’);
title([’8b) N=’,num2str(N)]);
ex82d.m
function ex82d(N,t)
% Plots the Nth partial sum of the solution to exercise 8.2c
% at time t
% example: ex82d(7,0.25)
x=0:0.02:1;
u=x.*0;
for k=1:N
c=2/(k*pi)*(1-cos(k*pi));
u=u+c*exp(-k*k*pi*pi*t)*sin(x.*pi*k);
end
plot(x,u);
xlabel(’x’); ylabel(’u’);
title([’8d) N=’,num2str(N),’, t=’,num2str(t)]);
ex82e.m
function ex82e(N,t)
% Plots the Nth partial sum of the solution to exercise 8.2e
% at time t
% example: ex82e(7,0.25)
x=0:0.02:1;
u=x.*0;
for k=1:N
c=-2*cos(k*pi)/(k*pi);
u=u+c*exp(-k*k*pi*pi*t)*sin(x.*pi*k);
end
109
plot(x,u,x,x,’r--’);
xlabel(’x’); ylabel(’u’);
title([’8e) N=’,num2str(N),’, t=’,num2str(t)]);
ex83.m
function ex83(N,t)
% Solves the problem from exercise 8-3 at time t.
% both by an explicit scheme and by using the
% N first terms of the formal solution.
% example: ex83(50,2)
x=0:0.02:1;
Dx= 0.02;
Dt= Dx*Dx/2;
% explicit scheme:
us=x.ˆ2 - x.ˆ3;
for t=0:Dt:t
for i=2:length(us)-1
u(i)=us(i) +Dt/(Dx*Dx)*(us(i-1) -2*us(i)+us(i+1));
end
u(1)=0; u(length(us))=0;
us=u;
end
% formal solution:
f=x.*0;
for k=1:N
c= -4*(1+2*cos(k*pi))/(k*k*k*pi*pi*pi);
f=f+c*exp(-k*k*pi*pi*t)*sin(x.*pi*k);
end
plot(x,u,x,f,’r--’)
xlabel(’x’); ylabel(’f’);
title([’8-3 N=’,num2str(N),’, t=’,num2str(t)]);
legend(’Explicit scheme’,’Formal solution’,1)
ex84.m
function u = ex84(N,x)
% Finds the sum of the N first terms of the
% Fourier sine series for eˆx
% example: ex84(5,0.5)
u=0;
for k=1:N
c=2*k*pi*(1-exp(1)*cos(k*pi))/(1+k*k*pi*pi);
u=u+c*sin(x*pi*k);
end
110
CHAPTER 8. ANSWERS CHAPTER 8
ex84c.m
function ex84c(N)
% Plots the partial sum of the Fourier series
% for eˆx. Also plots eˆx.
% Calls the function ex84.m.
% example: ex84c(50)
x=0:0.02:1;
u=x.*0;
for k=1:50
u(k)=ex84(N,x(k));
end
plot(x,exp(x),’r--’,x,u);
legend(’eˆx’,’Fourier series’,2);
title([’N=’,int2str(N)]);
ex86.m
function ex86(L,N,T,Dx,Dt)
% Solves the problem in exercise 8.6.
% in two different ways.
% example: ex86(2,6,0.01,0.05,0.001)
x=0:0.05:L;
f=exp(x);u=x.*0;
% Fourier:
for k=1:N
c=2*k*pi*(1-exp(L)*cos(k*pi))/(L*L+k*k*pi*pi);
u=u+c*exp(-k*k*pi*pi*T/(L*L))*sin(x.*pi*k/L);
end
% explicit scheme
ex=f;
for t=0:Dt:T
for i=2:length(ex)-1
e(i)=ex(i)+Dt/(Dx*Dx)*(ex(i-1) -2*ex(i)+ex(i+1));
end
e(1)=0;e(length(ex))=0;
ex=e;
end
plot(x,u,x,ex,’r--’);
legend(’Fourier series’,’explicit scheme’,2);
xlabel(’x’);
title([’N=’,num2str(N),’ t=’,num2str(T) ] );
111
ex87.m
function ex87(N)
% for exercise 8.7.a-e
% Computes the Nth partial sum of the Fourier series
% for eˆ(xˆ2), using the trapezoidal and Simpson’s rule
% example: ex87(100)
x=0:0.01:1;
f=x.*0; s=x.*0;
for k=1:N
ck=TrapRuleFourier(100,k);
f=f+ck*sin(x.*k*pi);
cks=SimpsonFourier(100,k);
s=s+cks*sin(x.*k*pi);
end
g=exp(-x.*x);
plot(x,f,x,s,’c--’,x,g,’r--’);
xlabel(’x’);
legend(’Trapez’,’Simpson’,’exact solution’,1)
title([’8-7 N=’,num2str(N)]);
function ck=TrapRuleFourier(n,k)
% n - intervals
% k - coefficient c_k
dx=1/n; x=0; ck=0;
for i=1:n-1
x=x+dx;
ck= ck + ex87a(x)*sin(k*pi*x)/n;
end
ck=ck*2;
function ck=SimpsonFourier(n,k)
% n - intervals
% k - coefficient c_k
dx=1/n; x=0; ck=0;
for i=1:n-1
x=x+dx;
ck= ck + 2*ex87a(x)*sin(k*pi*x) +4*ex87a(x-dx/2)*sin(k*pi*(x-dx/2));
end
ck=ck*2/(n*6);
function f = ex87a(x)
f=exp(-x*x);
CHAPTER 8. ANSWERS CHAPTER 8
112
ex87g.m
function ex87g(N)
% Computes an approximation of
% the formal solution to exercise 8.7
% for f(x)=sin(exp(cos(x))), and t=3, using Simpson’s rule.
% example: ex87g(100)
t=3;
x=0:0.01:1;
s=x.*0;
for k=1:N
cks=SimpsonFourier(100,k);
s=s+cks*exp(-k*k*pi*pi*t)*sin(x.*k*pi);
end
f= sin(exp(cos(x)));
plot(x,s,x,f,’r--’); xlabel(’x’);
title([’8-7g) N=’,num2str(N)]);
legend(’Solution at t=3’,’Initial condition’,2)
function ck=SimpsonFourier(n,k)
% n - intervals
% k - coefficient c_k
dx=1/n; x=0; ck=0;
for i=1:n-1
x=x+dx;
ck= ck + 2*ex87g(x)*sin(k*pi*x) +4*ex87g(x-dx/2)*sin(k*pi*(x-dx/2));
end
ck=ck*2/(n*6);
function f = ex87g(x)
f=sin(exp(cos(x)));
p851.m
function p851(Dx,Dt,t)
% Solves the problem from Project 1 at time t.
% The initial condition
% is placed in subfunctions.
% example: p851(0.1,0.0025,1)
x=0:Dx:1;
% Dt= Dx*Dx/4;
alpha=Dt/(Dx*Dx);
113
us=init2_f(Dx);
for t=Dt:Dt:t
for i=2:length(us)-1
u(i)=us(i)+alpha*(us(i-1)-2*us(i)+us(i+1));
end
u(1)=us(1)+2*alpha*(us(2)-us(1));
u(length(us))=us(length(us))+2*alpha*(us(length(us)-1)-us(length(us)));
% max(us)-max(u)
us=u;
end
ft=init2_f(Dx);
plot(x,us,x,ft,’r--’);
c1= 0.5*us(1)*us(1) +...
sum(us(2:length(us)-1).*us(2:length(us)-1)) +...
0.5*us(length(us))*us(length(us));
Dx*c1;
c2= 0.5*ft(1)*ft(1) +...
sum(ft(2:length(ft)-1).*ft(2:length(ft)-1)) +...
0.5*ft(length(ft))*ft(length(ft));
Dx*c2;
% find the integrals, using the trapezoid method.
c3= Dx*(0.5*us(1)+sum(us(2:length(us)-1)) +0.5*us(length(us)))
c4= Dx*(0.5*ft(1)+sum(ft(2:length(ft)-1)) +0.5*ft(length(ft)))
% find
max(us)-min(us)
% initial condition
function f=init_f(Dx)
x=0:Dx:1;
f=exp(x).*x.*(1-x);
% initial condition 2
function f=init2_f(Dx)
x=0:Dx:1;
f=3.14+cos(2*pi.*x);
p852.m
function p852(Dx,Dt)
% Solves the problem from Project 5.8.2. at time t=1.
114
CHAPTER 8. ANSWERS CHAPTER 8
% The initial condition and the thermal conductivity
% are placed in subfunctions.
% example: p852(0.1,0.0025)
x=0:Dx:1;
t=1;
% Dt= Dx*Dx/4;
alpha=Dt/(Dx*Dx);
us=init_f(Dx);
for t=Dt:Dt:t
for i=2:length(us)-1
u(i)=alpha*tc_k((i-0.5)*Dx)*us(i-1) +...
(1-alpha*(tc_k((i-0.5)*Dx)+tc_k((i+0.5)*Dx)))*us(i) +...
alpha*tc_k((i+0.5)*Dx)*us(i+1);
end
u(1)=0; u(length(us))=0;
% max(us)-max(u)
us=u;
end
% Equation (8.119)
c1= sum(us(2:length(us)-1).*us(2:length(us)-1))
Dx*c1
% Equation (8.120)
ft=init_f(Dx);
c2= 0.5*ft(1)*ft(1) +...
sum(ft(2:length(ft)-1).*ft(2:length(ft)-1)) +...
0.5*ft(length(ft))*ft(length(ft));
Dx*c2
% Equation (8.121)
c3=0.5*tc_k(Dx/2)*us(2)*us(2)/Dx;
for i=2:length(us)-2
c3 = c3 +tc_k((i-0.5)*Dx)*(us(i+1)*us(i+1) -...
2*us(i+1)*us(i)+ us(i)*us(i) )/Dx;
end
c3 = c3+0.5*tc_k(1-Dx/2)*us(length(us)-1)*us(length(us)-1);
c3
c4=0.5*tc_k(Dx/2)*(ft(1)*ft(1) -2*ft(1)*ft(2) +ft(2)*ft(2))/Dx;
for i=2:length(ft)-2
c4=c4 + tc_k((i-0.5)*Dx)*(ft(i+1)*ft(i+1) -...
2*ft(i+1)*ft(i) +ft(i)*ft(i))/Dx;
end
c4=c4 + 0.5*tc_k(1-Dx/2)*(ft(length(ft))*ft(length(ft)) -...
115
2*ft(length(ft))*ft(length(ft)-1) +ft(length(ft)-1)*ft(length(ft)-1))/Dx
c4
% initial condition
function f=init_f(Dx)
x=0:Dx:1;
f=x.*(1-x);
% thermal conductivity
function k=tc_k(x)
k=1+x;
116
CHAPTER 8. ANSWERS CHAPTER 8
Chapter 9
Answers Chapter 9
Exercises
9.1.4
a) Solving the equations for each year yields 5 slightly different values for a, ranging
from 0.0148 to 0.0169. This range is used as the initial edges for the bisection
method. The result is a = 0.0165, see program ex914.m.
b) See Figure 9.1.
c) The calculated population in 2000 is 5.7722 billion, the actual population was
6.0849. (Numbers taken from U.S. Census Bureau.) The error is 5.14%.
d) Newton’s method results in a = 0.0165 after three iterations. See program ex914.m.
9.1.5
a) Using Newton’s method results in r = 2.5512, a = 0.0169, after two iterations.
See program ex915.m
b) The calculated population in 2000 is 5.9271 billion, the actual population was
6.0849. The error is 2.59%.
9.1.6
a)
t=10
X
r0 Rte−at (R − r0 )
∂J
(r(t; a, r0 , R) − dt )
=
2
∂a
(r0 + e−at (R − r0 ))
t=0
t=10
X
∂J
R2 e−at
(r(t; a, r0 , R) − dt )
=
2
∂r0
(r0 + e−at (R − r0 ))
t=0
t=10
X
r02 (1 − e−at )
∂J
(r(t; a, r0 , R) − dt )
=
2
∂R
(r0 + e−at (R − r0 ))
t=0
117
CHAPTER 9. ANSWERS CHAPTER 9
118
9
6.5
x 10
calculated
actual population
6
5.5
5
4.5
4
3.5
3
2.5
1950
1955
1960
1965
1970
1975
1980
1985
1990
1995
2000
1995
2000
Figure 9.1: Excercise 9.1.4 b) World Population.
9
6.5
x 10
calculated
actual population
6
5.5
5
4.5
4
3.5
3
2.5
1950
1955
1960
1965
1970
1975
1980
1985
1990
Figure 9.2: Excercise 9.1.5 b) World Population.
119
b) For
a = 0,
r0 = R =
t=10
1 X
dt ,
11 t=0
t=10
t=10
X
X
∂J
r0 Rt(R − r0 )
0
(r(t; a, r0 , R) − dt )
(r(t; a, r0 , R) − dt )
=
=
2
2 = 0.
∂a
(r
+
(R
−
r
))
(r
+
(R
− r0 ))
0
0
0
t=0
t=0
When a = 0, we have that r′ (t) = 0, and r(t) = r(0) = r0 .
t=10
t=10
t=10
t=10
X
X
X
X
R2
∂J
dt = 0
r
−
(r(t;
a,
r
,
R)
−
d
)
=
(r(t; a, r0 , R) − dt )
=
=
0
0
t
2
∂r0
(r0 + (R − r0 ))
t=0
t=0
t=0
t=0
t=10
t=10
X
X
0
r02 (1 − 1)
∂J
(r(t; a, r0 , R) − dt )
(r(t; a, r0 , R) − dt )
=
=
2
2 =0
∂R
(r0 + (R − r0 ))
(r0 + (R − r0 ))
t=0
t=0
c) See program ex916.m
d) Newton’s method returns the starting position.
e) for
Newton’s method returns
e = (0.05, 5.0, 11.0),
(e
a, re0 , R)
(0.036, 5.285, 9.213).
f) for
Newton’s method returns
e = (0.01, 5.0, 11.0),
(e
a, re0 , R)
(0.0, r = 5.687, R = 5.687).
g) for
Newton’s method returns
e = (0.8, 5.0, 11.0),
(e
a, re0 , R)
(−19.23, r = 5.284, R = 8.526).
h) In section 5.5.2 we find R = 11.44, and a = 0.027. The initial guess is important.
120
CHAPTER 9. ANSWERS CHAPTER 9
Programs (MATLAB)
ex914.m
function ex914
%
% Bisection and Newton’s method for finding ’a’ in population growth
% Starting points: 0.0148 and 0.0169 for bisection,
% 0.0148 for Newton
% Bisection;
ls =
0.0148;
rs =
0.0169;
while ((rs-ls) > 0.00001)
midd = (ls+rs)*0.5;
if ( ex914a(ls)*ex914a(midd) < 0)
rs=midd;
else
ls = midd;
end
end
Bres = midd
% Newton:
x = 0.0148;
d =100;
j=0;
while (d > 0.00001)
xp = x - ex914a(x)/ex914d(x);
d= abs(x-xp);
x=xp;
j=j+1
end
Nres = x
% Create figure to compare with actual numbers:
a=Nres;
t=[0:50];
y=t+1950;
Pop=2.555*1e9*exp(t*a);
USC=[2555948654,2593751978,2635830950,2681188031,2729296850,
2780907497,2834042890,2890057665,2946761863,2999303775,
3041593413,3082587875,3138805626,3208557765,3279921533,
3349157095,3419597944,3489539835,3561584085,3636415012,
3711800786,3789459117,3865863923,3941725131,4016384740,
4089026773,4160182844,4231882118,4303414792,4377673820,
121
4452766336,4528969006,4609080226,4690922711,4771126065,
4852574467,4935986347,5021959865,5108492222,5194873063,
5282371928,5365708797,5448725522,5529987425,5610065463,
5690982026,5771360981, 5850822196,5929679830,6007529585,
6084907596];
plot(y,Pop,y,USC,’bo’)
legend(’calculated’,’actual population’,’Location’,’NorthWest’)
function Gs = ex914a(a)
dt = [2.555, 2.595, 2.635, 2.680, 2.728, 2.780]*1e9;
t = [1, 2, 3, 4, 5];
G= (2.555e9*exp(a*t) - dt(2:6)).*(2.555e9*t.*exp(a*t));
Gs = sum(G);
function dGs = ex914d(a)
dt = [2.555, 2.595, 2.635, 2.680, 2.728, 2.780]*1e9;
t = [1, 2, 3, 4, 5];
dG=2.555e9*2.555e9*2*t.*t.*exp(2*a*t) -2.555e9*dt(2:6).*t.*t.*exp(a*t);
dGs=sum(dG);
ex915.m
function ex915
%
% Newton’s method for finding ’a’ and ’r0’ in population growth
% Starting Points: a = 0.0165, r0 = 2.555 billion
global dt;
global t;
dt = [2.555, 2.595, 2.635, 2.680, 2.728, 2.780];
t = [0, 1, 2, 3, 4, 5];
r = 2.555;
a = 0.0165;
it = 0;
C2 = 42.0;
% Newton:
x = [r;a]
while (C2 > 1.0e-6)
M = [dFdr(x(1),x(2)), dFda(x(1),x(2)); dGdr(x(1),x(2)), dGda(x(1),x(2)) ];
V = [F(x(1),x(2));G(x(1),x(2))];
xn = x-inv(M)*V;
x=xn
C2 = abs(F(x(1),x(2))) + abs(G(x(1),x(2)))
122
CHAPTER 9. ANSWERS CHAPTER 9
it = it+1
end
r=x(1)
a=x(2)
% Create figure to compare with actual numbers:
t=[0:50];
y=t+1950;
Pop=r*1e9*exp(t*a);
USC=[2555948654,2593751978,2635830950,2681188031, 2729296850,
2780907497,2834042890,2890057665,2946761863,2999303775,
3041593413,3082587875,3138805626,3208557765,3279921533,
3349157095,3419597944,3489539835,3561584085,3636415012,
3711800786,3789459117,3865863923,3941725131,4016384740,
4089026773,4160182844,4231882118,4303414792,4377673820,
4452766336,4528969006,4609080226,4690922711,4771126065,
4852574467,4935986347,5021959865,5108492222,5194873063,
5282371928,5365708797,5448725522,5529987425,5610065463,
5690982026,5771360981, 5850822196,5929679830,6007529585,
6084907596];
plot(y,Pop,y,USC,’bo’)
legend(’calculated’,’actual population’,’Location’,’NorthWest’)
function f = F(r,a)
global t;
global dt;
v = (r*exp(a*t) -dt)*r.*t.*exp(a*t);
f = sum(v);
function g = G(r,a)
global t;
global dt;
v = (r*exp(a*t) -dt).*exp(a*t);
g = sum(v);
function dFdr = dFdr(r,a)
global t;
global dt;
v = 2*r*t.*exp(2*a*t) -dt.*t.*exp(a*t);
dFdr= sum(v);
function dFda = dFda(r,a)
global t;
global dt;
v = 2*r*r*t.*t.*exp(2*a*t) -dt*r.*t.*t.*exp(a*t);
dFda= sum(v);
123
function dGdr = dGdr(r,a)
global t;
global dt;
v = exp(2*a*t);
dGdr= sum(v);
function dGda = dGda(r,a)
global t;
global dt;
v = r*2*t.*exp(2*a*t)-t.*dt.*exp(a*t);
dGda= sum(v);
ex916.m
function ex916
%
% Solves the expression for ’J’ using Newton’s method
global dt;
global t;
dt = [5.284, 5.367, 5.450, 5.531, 5.611, 5.691, 5.769, 5.847, 5.925, 6.003, ...
6.080];
t = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
% NEWTON Starting point: a=0.025 r=5.0 R=11.0
a = 0.05;
r = 5.0;
R= 11.0;
it=0;
C2 = 300.0;
while (C2 > 1.0e-6)
x = [a;r;R];
M = [d2Jdada(a,r,R),d2Jdadr(a,r,R),d2JdadR(a,r,R);d2Jdadr(a,r,R),
d2Jdrdr(a,r,R),d2JdrdR(a,r,R);d2JdadR(a,r,R),d2JdrdR(a,r,R),
d2JdRdR(a,r,R) ];
V = [dJda(a,r,R);dJdr(a,r,R);dJdR(a,r,R)];
xn = x-inv(M)*V;
it = it+1;
a = xn(1);
r = xn(2);
R = xn(3);
C2 = abs(dJda(a,r,R)) + abs(dJdr(a,r,R))+ abs(dJdR(a,r,R));
end
% functions used
function J = J(a,r,R)
global t;
124
CHAPTER 9. ANSWERS CHAPTER 9
global dt;
v = (r*R./(r + exp(-a*t)*(R-r))) - dt;
J = 0.5*sum(v.*v);
function dJda = dJda(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
v= (Funcr-dt)*R*r.*t.*exp(-a*t)*(R-r)./(f.*f);
dJda = sum(v);
function d2Jdada = d2Jdada(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
drda = R*r.*t.*exp(-a*t)*(R-r)./(f.*f);
drda2 = R*r*(R-r)*t.*t.*exp(-a*t).*(exp(-a*t)*(R-r)-r)./(f.*f.*f);
tot = drda.*drda + (Funcr-dt).*drda2;
d2Jdada = sum(tot);
function d2Jdadr = d2Jdadr(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
drda = R*r.*t.*exp(-a*t)*(R-r)./(f.*f);
drdr = R*R*exp(-a*t)./(f.*f);
drdrda = R*R*t.*exp(-a*t).*((R-r)*exp(-a*t) -r)./(f.*f.*f);
tot = drdr.*drda + (Funcr-dt).*drdrda;
d2Jdadr = sum(tot);
function d2JdadR = d2JdadR(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
drda = R*r.*t.*exp(-a*t)*(R-r)./(f.*f);
drdR = r*r.*(1-exp(-a*t))./(f.*f);
drdRda = r*r*t.*exp(-a*t).*(-exp(-a*t)*(R-r) +2*R -r)./(f.*f.*f);
tot = drdR.*drda + (Funcr-dt).*drdRda;
d2JdadR = sum(tot);
function d2Jdrdr = d2Jdrdr(a,r,R)
125
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
drdr = R*R*exp(-a*t)./(f.*f);
drdr2 = 2*R*R*exp(-a*t).*(exp(-a*t)-1)./(f.*f.*f);
tot = drdr.*drdr + (Funcr-dt).*drdr2;
d2Jdrdr = sum(tot);
function d2JdrdR = d2JdrdR(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
drdr = R*R*exp(-a*t)./(f.*f);
drdR = r*r.*(1-exp(-a*t))./(f.*f);
drdrdR = 2*R*r*exp(-a*t).*(1-exp(-a*t))./(f.*f.*f);
tot = drdr.*drdR + (Funcr-dt).*drdrdR;
d2JdrdR = sum(tot);
function d2JdRdR = d2JdRdR(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
drdR = r*r.*(1-exp(-a*t))./(f.*f);
drdRdR = 2*r*r*exp(-a*t).*(exp(-a*t)-1)./(f.*f.*f);
tot = drdR.*drdR + (Funcr-dt).*drdRdR;
d2JdRdR = sum(tot);
function dJdr = dJdr(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
v= (Funcr-dt)*R*R.*exp(-a*t)./(f.*f);
dJdr = sum(v);
function dJdR = dJdR(a,r,R)
global t;
global dt;
Funcr = R*r./(r+exp(-a*t)*(R-r));
f = r+exp(-a*t)*(R-r);
v= (Funcr-dt)*r*r.*(1-exp(-a*t))./(f.*f);
dJdR = sum(v);
126
CHAPTER 9. ANSWERS CHAPTER 9
(Figure may be created using similar code as in 9.1.4 – 9.1.5.)