Scientific Computing and Programming Problems PDF
Scientific Computing and Programming Problems PDF
and
Programming Problems
by
Willi-Hans Steeb
International School for Scientific Computing
at
University of Johannesburg, South Africa
Yorick Hardy
Department of Mathematical Sciences
at
University of South Africa, South Africa
1) Matrix Calculus and Kronecker Product with Applications and C++ Pro-
grams
by Willi-Hans Steeb
World Scientific Publishing, Singapore 1997
ISBN 981 023 2411
http://www.worldscibooks.com/mathematics/3572.html
by Willi-Hans Steeb
World Scientific Publishing, Singapore 2006
ISBN 981 256 916 2
http://www.worldscibooks.com/mathematics/6202.html
by Willi-Hans Steeb
World Scientific Publishing, Singapore 2007
ISBN 981-256-916-2
http://www.worldscibooks.com/physics/6515.html
v
The International School for Scientific Computing (ISSC) provides certificate
courses for this subject. Please contact the author if you want to do this course
or other courses of the ISSC.
steebwilli@gmail.com
steeb_wh@yahoo.com
Home page of the author:
http://issc.uj.ac.za
vi
vii
Contents
Preface v
Notation x
1 Quickies 1
2 Bitwise Operations 11
4 Number Manipulations 22
5 Combinatorical Problems 35
6 Matrix Calculus 42
7 Recursion 53
8 Numerical Techniques 61
9 Random Numbers 72
10 Optimization Problems 73
11 String Manipulations 74
12 Programming Problems 76
Bibliography 93
Index 94
viii
x
Notation
:= is defined as
belongs to (a set)
The Pauli spin matrices are used extensively in the book. They are given by
0 1 0 i 1 0
1 := , 2 := , 3 := .
1 0 i 0 0 1
Quickies
1
2 Problems and Solutions
1 1 1
+ + +
12 23 n(n + 1)
13 + 23 + + n3
G~
`2P :=
c3
where G is the gravitational constant, ~ is the Planck constant divided by 2
and c is the speed of light. We have in the MKSA-system
m3
G = 6.6732 1011
sec2 kg
kgm2
~ = 1.0545919 1034
sec
m
c = 2.9979250 108 .
sec
Write a C++ program that calculates this quantity. Is the data type double
sufficient? Extend the calculation to find the Planck time interval and the Planck
mass r r
G~ c~
tP = , mP = .
c5 G
Quickies 3
Problem 11. Let n N. The map f : [0, 2n] [0, 2n] on the integers defined
by
f (0) = n
f (k) = 2n + 1 k for 0 < k n
f (k) = 2n k for n < k 2n
4 Problems and Solutions
Discuss.
(ii) Give a C++ implementation of this map. The user provides the n.
Problem 13. Given a vector of length n. Write a C++ program that checks
whether all entries are pairwise different.
k1 + k2 , k1 + k2
be simplified?
Problem 16. How would one calculate more efficiently (i.e. minimizing the
number of multiplications) the analytic function f : R R
for a given x.
Problem 20. (i) Let m be a mass, E an energy, a a length and ~ the Planck
constant (divided by 2). Show that
p
2m|E|a
:=
~
be dimensionless.
(ii) Let e be the charge, E the electric field, m the mass, the frequency and c
the speed of light (all in SI units). Is
eE
=
mc
a dimensionless quantity so that cases such as 1 can be studied?
(n0 + n1 + n2 )!
f (n0 , n1 , n2 ) =
n0 !n1 !n2 !
in SymbolicC++ utilizing the Verylong class and Rational class.
6 Problems and Solutions
with SymbolicC++ using the Verylong and Rational class and so find an ap-
proximation of .
G = 1 32 + 52 72 +
calculate?
(ii) Consider R4 and the vectors
1 1
1 0
u = , v = .
1 0
1 1
Calculate A.
tr(uu vv ).
tr(uu vv ) 0 ?
8 Problems and Solutions
Prove or disprove.
(ii) Let A be a 2 2 matrix. Calculate efficiently tr(A2 ).
// whileloop.cpp
#include <iostream>
using namespace std;
int main(void)
{
int x = 0; int t = 0; int p = 0;
while(t < 100) {
if(p==0) x = x + 2;
if(p==1) x = x - 1;
p = 1 - p;
t++;
} // end while
cout << "x = " << x << endl;
cout << "p = " << p << endl;
cout << "t = " << t << endl;
return 0;
}
Problem 36. The surface area of a torus with inner radius a and outer radius
b is a given by
A = 2 (b2 a2 ).
The formula for the volume of a torus is given by
2
V = (a + b)(b a)2 .
4
Simplify the calculation of V given A.
v = p2 p1 , w = p3 p1 .
Bitwise Operations
Problem 1. Let x, y {0, 1}. Show that the NOT-gate, AND-gate, OR-
gate, NAND-gate, NOR-gate and XOR-gate can be expressed using arithmetic
operations (i.e. addition, subtraction, multiplication).
would be possible. Note that the ant could also get stuck at (2, 0).
11
12 Problems and Solutions
#include <iostream>
using namespace std;
int main(void)
{
unsigned short i = 0xACE1u; // hex notation
cout << "i = " << i << endl;
unsigned short b;
unsigned short counter = 0u;
do
{
b = ((i)^(i >> 2)^(i >> 3)^(i >> 5)) & 1;
i = (i >> 1) | (b << 15);
counter++;
cout << "b = " << b << endl;
cout << "i = " << i << endl;
}
while(i != 0xACE1u);
cout << "leaving while-loop" << endl;
cout << "b = " << b << endl;
cout << "i = " << i << endl;
cout << "counter = " << counter << endl;
return 0;
}
Note that ^ is the XOR-operation, | is the OR-operation and & is the AND-
operation. Note that unsigned short has 16 bits.
(s0 , s1 , . . . , s2n 1 ) = s
f (x1 , x2 , x3 ) = x1 x2 x3 + x1 x2 x3 + x1 x2 x3 .
Find the truth table, the vector y and then using H(3) calculate the spectral
coefficients sj (j = 0, 1, . . . , 7).
x0 = x, y0 = x y
a reversible gate?
(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)
(0, 0, 0) 7 0, (0, 0, 1) 7 0
(0, 1, 0) 7 0, (0, 1, 1) 7 1
(1, 0, 0) 7 0, (1, 0, 1) 7 1
(1, 1, 0) 7 1, (1, 1, 1) 7 1.
14 Problems and Solutions
(0, 0, 0) 7 1, (0, 0, 1) 7 0
(0, 1, 0) 7 0, (0, 1, 1) 7 0
(1, 0, 0) 7 0, (1, 0, 1) 7 0
(1, 1, 0) 7 0, (1, 1, 1) 7 1.
xt+1 = xt yt , yt+1 = xt yt
Problem 10. (i) Let s1 (0), s2 (0), s3 (0) {+1, 1}. Study the time-evolution
(t = 0, 1, 2, . . .) of the coupled system of equations
s1 (t + 1) = s2 (t)s3 (t)
s2 (t + 1) = s1 (t)s3 (t)
s3 (t + 1) = s1 (t)s2 (t)
for the eight possible initial conditions, i.e. (i) s1 (0) = s2 (0) = s3 (0) = 1, (ii)
s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (iii) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (iv)
s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (v) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (vi)
s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (vii) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1,
(viii) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1. Which of these initial conditions are
fixed points?
(ii) Let s1 (0), s2 (0), s3 (0) {+1, 1}. Study the time-evolution (t = 0, 1, 2, . . .)
of the coupled system of equations
s1 (t + 1) = s2 (t)s3 (t)
s2 (t + 1) = s1 (t)s2 (t)s3 (t)
s3 (t + 1) = s1 (t)s2 (t)
for the eight possible initial conditions, i.e. (i) s1 (0) = s2 (0) = s3 (0) = 1, (ii)
s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (iii) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (iv)
s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (v) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (vi)
s1 (0) = 1, s2 (0) = 1, s3 (0) = 1, (vii) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1,
(viii) s1 (0) = 1, s2 (0) = 1, s3 (0) = 1. Which of these initial conditions are
fixed points?
Bitwise Operations 15
Problem 11. Let x1 (0), x2 (0), x3 (0) {0, 1} and let be the XOR-operation.
Study the time-evolution (t = 01, 2, . . .) of the coupled system of equations
x1 (t + 1) = x2 (t) x3 (t)
x2 (t + 1) = x1 (t) x3 (t)
x3 (t + 1) = x1 (t) x2 (t)
for the eight possible initial conditions, i.e. (i) x1 (0) = x2 (0) = x3 (0) = 0, (ii)
x1 (0) = 0, x2 (0) = 0, x3 (0) = 1, (iii) x1 (0) = 0, x2 (0) = 1, x3 (0) = 0, (iv)
x1 (0) = 1, x2 (0) = 0, x3 (0) = 0, (v) x1 (0) = 0, x2 (0) = 1, x3 (0) = 1, (vi)
x1 (0) = 1, x2 (0) = 0, x3 (0) = 1, (vii) x1 (0) = 1, x2 (0) = 1, x3 (0) = 0, (viii)
x1 (0) = 1, x2 (0) = 1, x3 (0) = 1. Which of these initial conditions are fixed
points?
Problem 12. Show that one Fredkin gate is sufficient to implement the XOR
gate.
Problem 13. Show that a b = a + b using (i) truth tables and (ii) properties
of boolean algebra (with a + 1 = 1).
Chapter 3
Problem 1. The straight line Hough transform maps a line in R2 into a point
in the Hough transform space. The polar definition of the Hough transform is
based on the representation of the lines by the parameters (, ) via the equation
= xj cos() + yj sin().
with 0 and [0, 2). All points (xj , yj ) of a given line correspond to a point
(, ) in the Hough transform space. Any point (xj , yj ) is mapped to a sinusoidal
curve in the Hough transform space. Consider the two points (x0 , y0 ) = (1, 0)
and (x1 , y1 ) = (0, 1) on a line. Find , .
Here f (n) denotes the n-th derivative. This identity is called generalized inte-
gration by parts. Let > 0. Find
Z 1
ex xn dx
0
16
Maps and Functions 17
on the Hilbert space of square integrable functions L2 (R) in terms of the Haar
basis
{ j,k (x) := 2j/2 (2j x k) : j, k Z }
where
1 x [0, 1/2]
(x) := 1 x (1/2, 1] .
0 otherwise
Notice that g f reads from right to left; it means first apply f , then apply g to
the result. Note that function composition is associative.
(i) Let f : R R, f (x) = x2 , and g : R R, g(x) = 3x 1. Find g f and
f g.
(ii) Write a C++ program which implements these compositions with x of data
type double.
where denotes the vector product. Using n+ we calculate L(u, v), M (u, v),
N (u, v) of the second fundamental form
2x 2x 2x
L(u, v) = n+ , M (u, v) = n+ , N (u, v) = n+ .
u2 uv v 2
Then the Gaussian curvature K(u, v) is given by
LN M 2
K := .
EG F 2
Write a SymbolicC++ program that calculates K and apply it to the Mobius
band given by
(2 v sin(u/2)) sin(u)
x(u, v) = (2 v sin(u/2)) cos(u) .
v cos(u/2)
// fcomposition.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
double x = 2.5;
cout << "f(" << x << ") = " << f(x) << endl;
cout << "g(" << x << ") = " << g(x) << endl;
cout << comp(f,g,x) << endl;
return 0;
}
Problem 10. Let N0 be the set of natural numbers including 0. The Cantor
pairing function f : N0 N0 N0 is defined by
1
f (x, y) = y + (x + y)(x + y + 1).
2
(i) Find the inverse function, i.e. given s = f (x, y) find x and y. Set
1 2
a := x + y, (a + a).
b :=
2
(ii) Give a C++ implementation utilizing Verylong of SymbolicC++.
Problem 12. (i) Let r > 0 (fixed) and x > 0. Consider the map
1 r
fr (x) = x+
2 x
20 Problems and Solutions
For example
ij 1 i j
k` = ( `i kj ).
2 k `
Write a SymbolicC++ program utilizing the class Rational and Verylong to test
whether there are solutions for n1 , n2 , n3 {1, 2, . . . , 50}.
Chapter 4
Number Manipulations
Problem 1. Let p be a prime number (base 10) with p > 2. Convert the
prime number into binary. Then consider this number in base 10. Test whether
this number is prime again. For example, consider the prime number 5. Then
in binary we have 101. Now 101 (base 10) is a prime number.
(i) Study this question for the first 10 prime numbers.
(ii) Write a C++ program that could do the job.
(3, 5), (5, 7), (11, 13), (17, 19), (29, 31),
(41, 43), (59, 61), (71, 73), (101, 103), (107, 109)
Let (p1 , p2 ) be a set of prime twins. Is
p1 p2 (p1 + p2 )
22
Number Manipulations 23
Then EP (a, b) denotes the elliptic group mod p whose elements (x, y) are pairs
of non-negative integers less than p satisfying
y 2 x3 + ax + b (mod p)
together with the point at infinity. Let p = 23 and consider the elliptic curve
y 2 = x3 + x + 1.
(i) Show that the condition (1) is satisfied.
(ii) To find the points in EP (a, b) one proceeds as follows:
1. For each x such that 0 x < p, calculate x3 + ax + b (mod p).
2. For each x from step 1 determine if it has a square root mod p. If not, there
are no points in EP (a, b) with this value of x. If so, there will be two values of
y that satisfy the square root operation root operation (unless the value is the
single y value of 0). These (x, y) values are points in EP (a, b). Find the points
in E23 (1, 1).
Problem 4. Apply the Chinese remainder theorem to solve the set of equations
x 7 (mod 8)
x 2 (mod 9)
x 1 (mod 5).
x b1 (mod m1 )
x b2 (mod m2 )
..
.
x bt (mod mt )
x = y1 b1 + + yt bt
m0 0
i mi = 1 (mod mi ).
We set yi = m0 0
i mi and correspondingly set
x = m0 0 0 0
1 m1 b1 + + mt mt bt .
x b1 + 0 + + 0 b1 (mod m1 ).
C = C ed mod n
M = C s mod n.
(ii) Show how the order r of C under modulo n arithmetic can be used to obtain
a linear diophantine equation for s.
(iii) Let p = 3, q = 17, e = 5 and M = 10. Find s and d.
input: p, g
output: q, r
q := 0; r := p
while(r <> 0) and LT(g) divides LT(r)) do
q := q + LT(r)/LT(g)
r := r - (LT(r)/LT(g))
where LT is the leading term, i.e. the term with the highest degree. Apply the
division algorithm to
p(x) = x4 1, g(x) = x3 x2 + x 1.
Problem 7. Consider the bijective spiral map on page 79 (problem 19). Can
we find an explicit expression for f ? Could a polynomial ansatz work
N
X
f (x, y) = cij xi y j , (x, y) Z Z.
i,j=0
Write a C++ program that checks whether there are solutions in the range
20 x 20.
#include <iostream>
using namespace std;
ostream& output(ostream& o)
{ o << "{" << predecessor << "}"; return o; }
}; // end class number
26 Problems and Solutions
class number<0>
{
public:
number<1> successor(void)
{ return number<1>(); }
}; // end class number<0>
int main(void)
{
number<0> zero;
cout << zero << endl;
cout << zero.successor() << endl;
cout << zero.successor().successor() << endl;
return 0;
}
Problem 10. The following program uses the Verylong class of Symbol-
icC++. What is the program doing?
// wormell.cpp
#include <iostream>
#include "verylong.h"
using namespace std;
int main(void)
{
Verylong two("2");
for(Verylong x("3");x<=Verylong("100");x+=2)
{
Verylong p("1");
Verylong t = x/two;
for(Verylong a("2");a<=t;a++)
{ for(Verylong b("2");b<=t;b++) { p = p*(x-a*b); } }
cout << "x = " << x << " " << "p = " << p << endl;
} // end x for loop
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string input = "PLEASE CONFIRM RECEIPT 471";
string output;
char t = 3;
for(int i=0;i<input.length();i++)
{
if((a <= input[i]) && (input[i] <= z))
output += (input[i] - a + t)%26 + a;
else if((A <= input[i]) && (input[i] <= Z))
output += (input[i] - A + t)%26 + A;
else if((0 <= input[i]) && (input[i] <= 9))
output += (input[i] - 0 + t)%10 + 0;
else output += input[i];
}
cout << "output = " << output << endl;
return 0;
}
Problem 12. Let n be a positive integer. We define the set Zn as the set of
nonnegative integers less than n
Zn := { 0, 1, 2, . . . , (n 1) }.
and we have an additive inverse (w), i.e. for each w Zn there exists a z such
that w + z = 0 mod n. Note that
if (a*b) = (a*c) mod n then b = c mod n if a is relatively
prime to n
28 Problems and Solutions
c0 i0 + c1 i1 + + cd1 id1 = M
smallestNumberOfCoins = M
if valueOfCoins = M
Pd1
numberOfcoins = k=0 ik
smallestNumberOfCoins = numberOfCoins
2437x + 51329y = 1 x, y Z
2. d <- 1
3. for i <- k downto 0
4. do x <- d
5. d <- (d*d) mod n
6. if d = 1 and x neq 1 and x neq n-1 then return true
7. if b_i = 1 then d <- (d*a) mod n
8. if d neq 1 then return true
9. return false
0 { }, n + 1 { n }.
For example
60
1230 = = 10.
6
Is the composition associative, i.e.
(mn)p = m(np) ?
Write a C++ program using templates (so that Verylong of SymbolicC++ can
also be used) that implements this composition.
Problem 19. Show that any positive integer n can be written uniquely as
n = 2j + k
30 Problems and Solutions
Problem 21. Let n be a positive integer. There are exactly as many irre-
ducible representations of the permutation group Sn (order of Sn is n!) as there
are partitions { pj } of n
n
X
pj = n, p1 p2 pn 0.
j=1
is given by
x2 (B(x))2 (1 x)B(x) + 1 = 0.
Problem 23. A perfect number is a natural number with the properties that
the sum of the factors gives twice the number, for example
26=1+2+3+6
(ii) Prove that if 2n1 p is perfect for p prime then p is a Mersenne prime and
p = 2n 1.
(iii) Prove that for any even perfect number q there exists n N such that
q = 2n1 (2n 1).
5x = 2 mod 3
4x = 7 mod 9
2x = 4 mod 10.
32 Problems and Solutions
18 = 7 + 4 + 4 + 1 + 1 + 1
* * * x
Number Manipulations 33
* *
-------
* * * *
* * * 0 +
-------
* * * *
Solve the problem when the asterisks can only be one of the prime numbers 2,
3, 5, 7.
x2 8y 2 = 17.
(i) Show that (x0 , y0 ) = (5, 1) is a solution. Show that (x0 , y0 ) = (7, 2) is a
solution.
(ii) Let n = 0, 1, 2, . . .. Show that if (xn , yn ) satisfy the equation, then
Problem 35. Let p and q be prime with p q. Solve for p and q such that
p + q is prime.
(i) Show that the Fermat numerbers satisfy the recurrence relation
with F0 = 3.
(ii) Calculate the first ten Fermat numbers using this recurrence relation and
the Verylong class of SymbolicC++.
(iii) Calculate the first ten Fermat numbers using this recurrence relation and
the BigInteger class of Java.
Combinatorical Problems
X = {2, 2, 3, 3, 4, 5, 6, 7, 8, 10}.
35
36 Problems and Solutions
rectangular array such that the two ends of each dumbbel are in two horizontally
or vertically adjacent boxes and no two dumbells have ends which share a box.
Obviously, A(r, n) = 0 if r > n. For example a configuration with n = 3 and
r = 3 is
with the initial conditions A(1, 1), A(1, 2), A(2, 2) and A(0, n) = 1. Use this
implementation to find A(1, 5), A(2, 5), A(3, 5), A(4, 5), A(5, 5).
(iii) Give a C++ implementation of this recurrence together with the initial
conditions.
Problem 5. (i) Let N0 be the set of all positive integers including 0. Let
i, j, k N0 . Find all solutions of i + j + k = 3. Write down the solution in
lexigographical order.
(ii) Write a C++ program that finds all solutions of i + j + k = n for a given
n N0 .
(iii) Write a C++ program that implements this recurrence relation with the
initial value s1 = 1.
Problem 9. Show that the number of ways in which n different objects can
be arranged in a a ring, if only relative order matters, is (n 1)!. First give an
example with 3 objects.
Problem 10. (i) How many n-digit ternary sequences (using only 0,1,2) are
there with k 1s?
(ii) Find the sequences for n = 3 and k = 2.
(iii) Write a C++ program that finds these sequences for given n and k in
lexicographical order.
Problem 11. Suppose that we list all the 2n 1 nonempty subsets of the set
of numbers { 1, 2, . . . , n }. Then, for each subset, we write down the product of
its elements. Finally, we add these 2n 1 numbers to obtain the number sn .
Obviously, s1 = 1. For n = 3 the seven products we obtain are 1, 2, 3, 1 2, 1
3, 2 3 and 1 2 3. Thus s3 = 1 + 2 + 3 + 2 + 3 + 6 + 6 = 23. Find a recurrence
relation for sn . Write a C++ program that implements this recurrence relation
with the initial value s1 = 1.
Problem 14. Show that the number of ways of writing the positive integer n
as a sum of positive integers, where the order of the summands is significant, is
2n1 for n 1. For example, for n = 3 we have 3 = 3, 3 = 2 + 1, 3 = 1 + 2,
38 Problems and Solutions
3 = 1 + 1 + 1.
Problem 15. The number xn of steps required to solve the Chinese rings
puzzle with n rings satisfies x1 = 1 and the recurrence relation
2xn n odd
xn+1 =
2xn + 1 n even
where n = 1, 2, . . ..
(i) Prove that xn+2 = xn+1 + 2xn + 1.
(ii) Find a formula for xn .
p1 p2 pk 1
such that
p1 + p2 + + pk = n.
Each pj is called a part. For example, 18 = 7 + 4 + 4 + 1 + 1 + 1 is a partition of
18 into 6 parts. The number of partitions of n into k parts is denoted by p(n, k).
(i) Find p(7, 3).
(ii) Show that the recurrence for p(n, k) is given by
Problem 18. The Bell numbers count (starting from 0) the ways that n
distinguishable objects can be grouped into sets if no set can be empty. Thus
Combinatorical Problems 39
Hence for n = 3 there are five partitions and thus the third Bell number is 5.
(i) Let Pn denote the nth Bell number, i.e. the number of all partitions of n
objects. Then we have
1 X kn
Pn = .
e k!
k=0
S = { 0, 1, 2, . . . , N }
How many pairs (m, n) (m, n S) can be formed with the condition that m < n.
Problem 20. Let n be the number of discrete symbols s1 , s2 , . . . ,sn that can
be used. Let m be the length of the message string. Find the number M of
messages. Then consider the special case n = m = 2.
Problem 21. Consider a bitstring of length m which has exactly m1 ones and
m2 zeros (m1 + m2 = m).
(i) Find the number of different possible bitstrings.
(ii) Consider the special case m = 4, m1 = m2 = 2. Write down the bitstrings
in lexicographical order.
Problem 24. A dice is thrown twice. The first throw determines the tens
digit and the second throw the ones digit of the two-digit number. Find the
probability that this two-digit number is a perfect square.
Problem 25. How many different numbers of 7 digits can be formed with the
digits 1122334 ?
Problem 27. Suppose three fair coins are flipped. Let X be the event that
they same face. Let Y be the event that there is at most one head. Show that
X and Y are independent.
Problem 28. The Stirling number of the second kind S(n, k) is the number
of partitions of a set with n elements into k classes. Let b , b be Bose creation
and annihilation operators with the commutation relations
[b, b ] = bb b b = I
where I is the identity operator. Then S(n, k) can be defined by
n
X
(b b)n = S(n, k)(b )k bk .
k=1
Let n = 3. Use this definition to find S(3, 1), S(3, 2), S(3, 3).
Problem 29. Let n 1. Let a1 , a2 , . . . ,an be real numbers. How many terms
are there in the sum
X X X
aj1 aj2 aj3 .
1j1 <j2 <j3 n
Matrix Calculus
42
Matrix Calculus 43
Consider
1 1
A= .
1 1
(i) Calculate eA .
(ii) Calculate f2,2 (A), the norm of A and the error estimation. The norm is
given by
kAk := max kAxk
kxk=1
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
.
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
We say that the vector t = (t0 , t1 , . . . , t2n2 ) defines the Toeplitz matrix T .
Thus the 4 4 Toeplitz matrix defined by the vector t = (t0 , t1 , t2 , t3 , t4 , t5 , t6 )
44 Problems and Solutions
is
t3 t2 t1 t0
t4 t3 t2 t1
T = .
t5 t4 t3 t2
t6 t5 t4 t3
Write a C++ program that generates the Toeplitz matrix T from a given vector
t. Vice versa given a Toeplitz matrix T find the vector t.
Then
2
p p p
X 2 X n + 2 X
k exp( Aj ) fn,1 (A1 , A2 , . . . , Ap )k kAj k exp kAj k
j=1
n j=1
n j=1
and
Xp
lim fn,1 (A1 , A2 , . . . , Ap ) = exp Aj .
n
j=1
For p = 2 we obtain
eA1 +A2 = lim (eA1 /n eA2 /n )n . (1)
n
Let
0 1 0 0 0 1
A= , A1 = , A2 = .
1 1 0 1 1 0
Then A = A1 + A2 . Note that [A1 , A2 ] 6= 0.
(i) Calculate eA by diagonalizing A.
(ii) Calculate eA using equation (1).
(iii) Calculate f2,1 (A1 , A2 ) and the error estimation.
1 w2 w4 . . . w2(n1)
Fn :=
.
.. .. .. .. ..
. . . .
(n1)2
1 wn1 w2(n1) ... w
where w := e2i/n is the n-th root of unity. We obtain the discrete Fourier
transform from
(x1 , x2 , . . . , xn )T = Fn (x1 , x2 , . . . , xn )T .
Matrix Calculus 45
Apply F4 to the data (1, 0, 0, 1)T and (0, 1, 1, 0)T and interpret the results to
find the underlying periodicity.
Problem 7. (i) The discrete Fourier transform over n points can be written
in matrix form
1 1 1 ... 1
1 2 n1
w w ... w
2 4 2(n1)
1 w w . . . w
Fn :=
... .. .. .. ..
. . . .
n1 2(n1) (n1)2
1 w w ... w
where w = e2i/n is the n-th root of unity. Show that the matrix 1 Fn is
n
unitary.
(ii) Use trigonometric interpolation to find
A AA = A (AA ) = AA (A A) = A A.
0 1 1 0
1 1 0 0 1
.
2 1 0 0 1
0 1 1 0
Problem 13. How would one store a matrix using a linked list?
12 + 22 + 32 + + n2 = an3 + bn2 + cn
equations and write a C++ program using Gauss elimination that finds the
solution.
A B = (ajk bjk ).
Problem 18. Consider the set, M , containing all matrices of M2 (R) of the
form
a b
b a
where a, b R. Mapping this matrix onto a + i b we obtain a field iso-
morphism between M and C. Write a C++ program using complex<T> and
vector<vector<T> > and the function
void isomorphism(complex<T>& z,vector<vector<T> >& m)
that maps a complex number to the corresponding 2 2 matrix.
2uuT
In T A
u u
can be done as follows.
48 Problems and Solutions
Step 2. for j = 1, 2, . . . , n do
= u1 a1j + u2 a2j + + un anj
=
for i = 1, 2, . . . , n do aij = aij ui
p1 (x) = a0 + a1 x + + an xn , p2 (x) = b0 + b1 x + + bm xm
The determinant of this matrix is proportional to the resultant of the two poly-
nomials. If the resultant vanishes, then the two polynomials have a non-trivial
greates common divisor. Implement this algorithm in SymbolicC++ where
aj , bj Q and apply it to the polynomials
Problem 24. Write a C++ program that transposes a square matrix in-place.
randomly. An ant at entry (0, 0) can only move to the right or down (not diag-
onal) when this entry contains a 1. Write a C++ program that check whether
the ant could reach the entry (n 1, n 1). For example, consider the matrix
1 0 0 0 0
1 1 1 0 0
1 0 1 0 1.
0 0 1 1 0
0 0 0 1 1
would be possible. Note that the ant could also get stuck at (2, 0).
Problem 28. Apply the Leverrier method to find the determinant of the
matrix
1 0 1
A() = 0 1 0
1 0
where R. What is the condition on such that the inverse of A() exists?
(I2 A)1 = I2 + A + A2 + .
Cx(t + 1) = Rx(t) + b, t = 0, 1, . . .
Write a C++ program that calculates the right-hand side of the inequality for
a given matrix. Apply the complex class of STL. Apply it to the matrix
i 0 0 i
0 2i 2i 0
A= .
0 3i 3i 0
4i 0 0 4i
where the summation is over all n! permutations of the set [n] := {0, 1, . . . , n1}.
Give an implementation with SymbolicC++ to find the permanent of a given
Matrix Calculus 51
matrix A.
where the summation is over all n! permutations of the set [n] := {0, 1, . . . , n1}
and sgn() equals +1 if is an even permutation and equals 1 if is an odd
permutation.
F = njk , j, k = 0, 1, . . . , n 1.
First show that the determinant of the 3 3 matrix is nonzero. Apply two
different methods (Gauss elimination and the Leverriers method) to find the
solution. Compare the two methods and discuss.
Recursion
with n 0 and the initial value h[0] = 1. The Catalan number h[1], h[2], . . .
arise in a number of problems in combinatorics. Write a C++ program that
finds the Catalan numbers h[1], h[2], . . . , h[6] using the Catalan recurrence.
53
54 Problems and Solutions
Write a C++ program that implements this iteration for p = 3 and a = 27.
Problem 4. Let 0 < x < 2. The computation of 1/x can be done with
addition and multiplication using the following recurrence relation
Apply integration by parts to find a recursion relation for In , i.e. express In with
In1 , In2 . Note that
Z /2 Z /2
I1 = cos(x)dx = 1, I2 = cos2 (x)dx = .
0 0 4
where n = 0, 1, . . . and
Z /4
I0 = dx =
0 4
Z /4
/4
I1 = tan(x)dx = ln(cos(x))|0 = ln(cos(/4)) + ln(cos(0)) = ln( 2).
0
Problem 7. Let x [0, 1]. Then x can be approximated by the sequence of
polynomials
1
pk+1 (x) = pk (x) + (x (pk (x))2 ), k = 0, 1, 2, . . .
2
Recursion 55
and k the sequences converges pointwise to x with p0 (x) = x. Write
a
C++ program that implements this sequence to find an approximation for x.
where
x0 = 1, y0 = 2.
Then
lim xk =
.
k 2
Write a C++ program that implements this iteration and thus finds an approx-
imation of /2.
Problem 10. (i) Let r be a real nonzero number. Then 1/r can be calculated
to ever increasing accuracy applying the map
xt+1 = xt (2 rxt ), t = 0, 1, . . .
provided the initial estimate x0 is sufficientlty close to 1/r. The number of digits
of accuracy approximately doubles with each iteration. First find the fixed points
of the map. Let r = 3 and x0 = 2. Find x1 , x2 , . . . . Discuss.
(ii) The same iteration can be applied to find the multiplicative inverse modulo
any power of 2. For example, to find the multiplicative inverse of 5, modulo 256,
we start with x0 = 1 (any odd number will do). Then
x1 = x0 (2 5 x0 ) = 3
x2 = 3(2 5 (3)) = 51
x3 = 51(2 5 (51)) = 13107.
Thus 13107 mod 256 = 205. Thus the multiplicative inverse of 5 (modulo 256)
is 205. Write a C++ program that implements this algorithm.
56 Problems and Solutions
s0 , s1 , s2 , . . . or t0 , t1 , t2 . . .
t0 , t1 , t2 , . . .
sj := t0 + t1 + + tj j = 0, 1, 2, . . .
tj
tj+1 = f (tj ) = .
j+1
Problem 13. Let m be a positive integer and x be a fixed real number. Then
we can calculate cos(mx) using the recursion
Write a C++ program that implements this recursion. Use the values m = 10
and x = 0.1.
xt+1 = xt + 5yt
yt+1 = xt + yt
58 Problems and Solutions
with z0 = x0 /y0 = 1.
where p(1, 1) = 1.
Problem 22. Consider the alphabet {A, B, C} and the Fredholm subsitution
Start of with A and find the sequence. Then set A = C = 0 and B = 1 and find
the bitstring.
Ik+2 () 2 cos()Ik+1 () + Ik () = 0, k = 0, 1, . . .
Then
X
X m X
X
P (x) = 1+ ck1 cmk xm = 1+x cmk xmk ck1 xk1 = 1+xP 2 (x)
m=1 k=1 k=1 m=k
Problem 26. Let I (x) be the modified Bessel function. For the asymptotic
expansion we have
I+1 (x) X
cj xj
I (x) j=0
Numerical Techniques
or
X xk
ex := . (2)
k!
k=0
The above two formulae give methods to calculate ex numerically. The second
expression is more convenient for such a purpose, because the convergence of (2)
is better than of (1). Is there a way to combine the two definitions for a more
rapidly converging expression for ex ?
Problem 2. Calculating 2 an elementary and ancient recursion consists of
the double sequence
with j = 0, 1, . . . and
pj
lim = 2.
j qj
(i) Calculate the first three terms with the initial values p0 = q0 = 1.
(ii) Give an error estimation with j := | 2 pj /qj |.
(iii) Write the problem in matrix notation and solve it.
61
62 Problems and Solutions
where n 2, (1/f )[k] denotes the kth derivative of 1/f and j = 0, 1, 2, . . . with
x0 to be the initial value. Show that for n = 2 we obtain Newtons method and for
n = 3 we obtain Halleys method. Derive the iteration for the case n = 4. Write
a C++ program for this case with the analytic function f (x) = sin(2x) sinh(x)
and the initial condition x0 = 1.
ax2 + bx + c = 0, a 6= 0.
Problem 5. Let a > 0. Find an iteration to approximate a. Use the fact
that if x (x > 0) is the actual square root of a, then x = a/x; that is, the two
factors x and a/x are equal.
Problem 7. (i) Provide a fast algorithm to calculate 2.
Numerical Techniques 63
(ii) Provide a fast algorithm to calculate the golden mean number = (1+ 5)/2.
Calculate the left and right hand side for n = 1 and n = 10.
du
= u(t 1).
dt
We can find the solution with the ansatz
u(t) = Cet .
= e .
and , respectively, are measured from the line of the fixed pivots. The moving
links of fixed length are a, b, c. The fixed link is d. This provides us with the
equation
b2 = c2 + d2 + a2 2dc cos() 2ac cos() cos() 2ac sin() sin() + 2ad cos().
2) Positivity
Ni,k (x) 0.
3) Local support
Ni,k (x) = 0 for x
/ [xi , xi+k ].
Numerical Techniques 65
Let m = 4 and
Let k = 2. Find N0,2 (x), N1,2 (x) and N2,2 (x). Draw the functions.
Problem 15. Let f be a continuos function in the interval [a, b] (b > a). Then
n b
ba X k(b a)
Z
lim f a+ = f (x)dx.
n n n a
k=1
Problem 16. (i) Use the class Derive of SymbolicC++ to find the derivative
of
y = 2x3 5x 1
at the point x = 2. Use the data type double for x.
(ii) Use the class Derive of SymbolicC++ and the class complex over double
to find the derivative of the complex-valued function
w = 2z 2 5z 1
at the point z = i.
Problem 17. Let r be a real number with r 6= 0. Then 1/r can be calculated
to ever increasing precision by using the iteration
xt+1 = xt (2 rxt ), t = 0, 1, 2, . . .
provided the initial value x0 is sufficiently close to 1/r. The number of digits of
precision approximately doubles with each iteration. Write a C++ program to
66 Problems and Solutions
find the inverse of r = 2 with the initial value x0 = 0.8. Why does the initial
value x0 = 1 not work?
Problem 18. In C and C++ the function fabs finds the absolute value of
a floating point number. How can fabs be replaced by an if condition and
multiplication by 1.0?
#include <iostream>
using namespace std;
float invSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)& x; // get bits for floating value
i = 0x5f3759df - (i >> 1); // initial guess
x = *(float*)& i; // convert bits back to float
x *= 1.5f - xhalf*x*x;
x *= 1.5f - xhalf*x*x;
return x;
}
int main(void)
{
float x1 = 10.0f;
float r1 = invSqrt(x1);
cout << "r1 = " << r1 << endl;
float x2 = 100.0f;
float r2 = invSqrt(x2);
cout << "r2 = " << r2 << endl;
return 0;
}
x1 = sin(x1 + x2 ), x2 = cos(x1 x2 )
Problem 21. Given a polynomial of degree n which admits n real roots. Write
a C++ program using the Newton method that finds all real roots. Apply the
program to the polynomial
Problem 22. A polygon is a closed plane figure with n sides. If all sides and
angles are equivalent the polygon is called regular. The area of a planar convex
polygon with vertices
is given by
n1
1X
A= (xi yi+1 xi+1 yi ), xn x0 , yn y0 .
2 i=0
A polygon in the plane R2 is a closed figure with n sides. If all sides and angles
are equal the polygon is called regular. The area of a planar convex polygon
with vertices
(x0 , y0 ), (x1 , y1 ), . . . , (xn1 , yn1 )
is given by
n1
1 X
A= (xj yj+1 xj+1 yj ) , xn x0 , yn y0 .
2 j=1
(i) Write a C++ program that finds the area of a given planar convex polygon.
Apply the modulus operator % to identify n and 0.
68 Problems and Solutions
(ii) Write a Java program that finds the area of a given planar convex polygon.
Apply the modulus operator % to identify n and 0.
where hx0 i and hxj i are, respectively, the mean values of the epochs starting at
x0 and xj and 0 and j the corresponding standard deviations. Write a C++
program that find the correlation coefficient for the logistic map
xt+1 = 4xt (1 xt ), t = 0, 1, 2, . . .
Problem 24. The standard Hermite polynomial satisfy the recursion relations
dHn (x)
Hn+1 (x) = 2xHn (x) 2nHn1 (x), = 2nHn1 (x)
dx
with H0 (x) = 1. Combining these two relations we get the recursion relation
d
Hn+1 (x) = 2x Hn (x).
dx
Write a C++ program using SymbolicC++ which implement this recursion re-
lation.
Use Newtons method to solve this system of equations to find the eigenvalues
of A.
#include <iostream>
using namespace std;
int main(void)
{
double eps = 1.0, x = 2.0, y = 1.0;
while(y < x) { eps *= 0.5; x = 1.0 + eps; }
eps *= 2.0;
cout << "eps = " << eps;
}
Problem 28. Let x > 1. Then ln(x) can be calculated using the iteration
x0 = x
2x
xj+1 = p j , j = 0, 1, 2, . . .
1 + 1 + 2j xj
Write a C++ program that implements this iteration. Apply it to x = 10 and
x = e.
Problem 29. The junction between p- and n-type semiconductors has prop-
erties which make it the basis of many electronic devices. For a p-n junction
diode we have the equation
1/2
20 r (nA + nD )(VD U )
d=
enA nD
where d has the dimension of a length (thickness of the deplection layer) and
Write a C++ program that finds d in dependence of the voltage U with 10V
U 0V and step size 0.5V and the capacity
C(d) = 0 r a/d.
70 Problems and Solutions
All the units are in the MKSA system. Thus the result for d will be in meters
and the result for the capacity C will be in Farad (= s4 A2 /m2 kg).
(x 2)2 = ln(x).
sin(b) + a b + c d + (a b).
|{z}
Numerical Techniques 71
(i) Write this mathematical expression as a binary tree with the root indicated
by the underbrace. Then evaluate this binary tree from bottom to top with the
values a = 2, b = /2, c = 4, d = 1.
(ii) Am alternative to represent a mathematical expression as tree is multiex-
pression programming. Use multiexpression programming to evaluate the math-
ematical expression given above.
Problem 34. Find an approximation of 30 utilizing
30 = 25 + 5 = 5 1 + 0.2.
Chapter 9
Random Numbers
using the random numnber generator described in problem 7, chapter 10, page
250, Problems and Solutions in Scientific Computing. Compare to the exact
result by solving the integral.
72
Chapter 10
Optimization Problems
1 1 1 1
1 0.5 0.25 x1 0.5
1 0 0 x2 = 0 .
1 0.5 0.25 x3 0.5
1 1 1 2.0
73
Chapter 11
String Manipulations
n
X vi v
i
H(S) = log .
i=1
` `
This can be regarded as the average information per position in the sequences.
Write a C++ program that implements H(S).
Problem 4. Write a C++ program that find the first character in an ASCII
string that occurs only once. Find a solution that minimizes the number of
comparisons between characters. Note that \0 denotes the null character.
74
String Manipulations 75
w1 t = w1
t w2 = w2
au t bv = a(u t bv) + b(au t v)
Problem 6. (i) Write a C++ program that uses the string class and the line
string* sa = new string[N];
Programming Problems
#include <iostream>
using namespace std;
int main(void)
{
int* array = new int[20];
76
Programming Problems 77
// wavelets.cpp
#include <iostream>
using namespace std;
double H(double x)
{
if((x >= 0.0) && (x <= 0.5)) return 1.0;
if((x > 0.5) && (x <= 1.0)) return -1.0;
return 0.0;
}
int main(void)
{
double r1 = transform(H,-4.0,0.5,4.0);
cout << "r1 = " << r1 << endl;
double r2 = transform(H,-1.6,2.0,4.0);
cout << "r2 = " << r2 << endl;
double r3 = transform(H,2.6,4.0,-10.0);
cout << "r3 = " << r3 << endl;
return 0;
}
3x2 2y 2 4z 2 + 54 = 0, 5x2 3y 2 7z 2 + 74 = 0.
Write a C++ program that finds all integer solutions in the range 0 x 100,
0 y 100, 0 z 100.
Problem 9. Write a C++ program that finds the maximum of the function
x4 + y 4 + 79 = 48xy.
Write a C++ program that finds all solutions in the range 10 x 10 and
10 y 10.
Problem 11. LISP is latently typed, i.e. does not explicitly specify the
underlying data type for variables. Is it possible to achieve the same with C++?
In other words, can be construct an abstract datatype in C++ such that the
underlying data type can be stored and used in a form that does not explicitly
state the underlying data type? Give a possible implementation in standard
C++.
Problem 12. Write a C++ program that finds the numbers of integer solu-
tions of the equation i1 + i2 + i3 = 12 satisfying the following constraints
0 i1 6, 0 i2 6, 0 i3 3.
Programming Problems 79
Problem 13. The vector class of the Standard Template Library in C++
is a container class. Arithmetic operation such as addition of vectors are not
implemented. Write a C++ program that overloads + so that one can add two
vectors.
Problem 14. Let x be the number of man, y be the number of woman and
z be the number of children. Altogether there are 100 persons. Given 100 kg
of potatos. Every man gets 3 portions, a woman gets 2 portions and a child
gets 1/2 a portions. Find all (integer) solutions. We have two linear equations
with three unkowns, however we have the constraint that x, y, z are nonnegative
integers. Write a C++ program that finds all these integer solutions.
Problem 15. Consider a linked list. Determine if the linked list loops using
only two pointers.
Problem 16. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Consider the program (page 25)
au.cpp. Where is the amplitude? Extend the program to two or more sine
waves (for example frequency 880 besides 440).
Problem 17. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Consider the program (page 8)
SineSound.java. Run the Java program with the first line (page 10) changed
to
...new File("sine.au"));
with WAVE also changed. Compare to the previous problem. Extend the program
to get in more frequencies.
Problem 18. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Consider the program (page 31)
LGB.java. Rewrite the program in C++ either with the vector class of STL or
plain (just functions).
Problem 19. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Consider the program (page 44)
Noise.java. Rewrite the program into C++.
Problem 20. The problem refers to the book Mathematical Tools in Sig-
nal Processing with C++ and Java Simulations. Consider the Matlab Filter
Implementation (page 49). Rewrite the code in C++.
Problem 21. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Consider the program (page 60)
80 Problems and Solutions
Problem 22. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Give a Java implementation of
the two-dimensional convolution (page 61).
Problem 23. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Implement the two-dimensional
Fourier transform in C++ (page 72).
Problem 24. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Implement the two-dimensional
Cosine transform (page 76).
Problem 25. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Use the complex class of STL and
do someting useful with the z-transform (chapter 8).
Problem 26. The problem refers to the book Mathematical Tools in Sig-
nal Processing with C++ and Java Simulations. Implement two-dimensional
wavelets (page 89).
Problem 27. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. In the C++ program (page 138)
the total number of distinct observations is 2. Extend the program to more
observations.
Problem 28. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Extend the C++ code fragment
(page 205) to a complete C++ program.
Problem 29. The problem refers to the book Mathematical Tools in Signal
Processing with C++ and Java Simulations. Implement the decompression
procedure (page 216) in C++.
Problem 30. Write a Java program Gauss.java that implements Gauss elim-
ination to solve linear equation with n equations and n unkowns. Apply the
program to the system
0 0 1 x0 1
0 1 0 x1 = 2 .
1 0 0 x2 3
Programming Problems 81
Problem 31. Which of the following C++ program fragments will loop for-
ever?
int i = 1;
while(i != 0) i = i + 1;
int j = 1;
while(j != 0) j = 2*j + 1;
double x = 1.0;
while(x != 0) x = x/2.0;
Problem 33. How would one store a matrix using a linked list?
Chapter 13
Applications of STL in
C++
Problem 4. Write a useful C++ program that uses the function find_if().
The function find_if takes a predicate (function object or function) as param-
eter.
82
Applications of STL in C++ 83
Example. Consider
A = {1, 2, 3, 4, 5}
and
B = {true, f alse}.
Let
g = {(1, f alse), (2, true), (3, true), (4, f alse), (5, true)}
then g(2) = true, g(4) = f alse etc. The function g associates with each number
in A the value in B which indicates whether the number is prime.
Example. Let f and g denote the two functions from the examples above and
(we rename the sets for clarity)
A = {one, two, three, f our, f ive},
B = {1, 2, 3, 4, 5},
C = {true, f alse}.
84 Problems and Solutions
In other words (gf )(two) = g(f (two)) = g(2) = true and (gf )(f our) = f alse.
Problem 7. The group table for a group with three elements a,b,e is given
by
e a b
e e a b
a a b e
b b e a
where e is the neutral element (identity) of the group. Write a C++ program
that implements this group table using the map class and the string class. For
example, the user should enter a*b and the output should be e.
Problem 8. The STL set class is a template class. Thus we may construct for
example set<int>, set<double>, and set<string>. In mathematics sets are
not required to be of a homogeneous type. We should be able to store for example
both integers and strings in a mathematical set. Implement a class AnyData such
that set<AnyData> can contain elements of any type. For example, it should be
possible to do the following:
set<AnyData> s;
s.insert(2);
s.insert(string("string"));
s.insert(3.5);
set.insert(2);
Applications of STL in C++ 85
M := { c C : c, c2 + c, (c2 + c)2 + c, . . . , 6 }.
zt+1 = zt2 + c, t = 0, 1, 2, . . .
with the initial value z0 = 0 and whether zt escapes to infity. For example
c = 0 and c = 1/4 + i/4 belong to the Mandelbrot set. The point c = 1/2 does
not belong to the Mandelbrot set. Write a C++ program using the complex
class of STL to find the Mandelbrot set. The output should be written to a file
Mandel.pnm (portable anymap utilities). This file can then be used to display
the fractal.
map<int,pair<int,int> >
We may think of a priority queue as a set of tasks with priorities. At any time
a new task can be added. A task can also be removed from the priority queue,
but this can only be the one with the highest priority. If this highest priority
is shared by more than one task, we do not care which one is taken. Write a
C++ program that uses the priority queue from STL. Apply it to floating point
numbers so that bigger numbers get a higher priority. Apply it to strings so that
strings lexicographicaly higher get a higher priority (case sensitive).
Problem 12. The ancient puzzle of the Tower of Hanoi consists of a number of
wooden disks mounted on three poles, which are in turn attached to a baseboard.
The disks each have different diameters and a hole in the middle large enough
for the poles to pass through. At the beginning all disks are on the left pole
with the smallest at the top, the second smallest one down etc. The object of
the puzzle is to move all the disks over to the right pole, one at the time, so that
they end up in the original order on that pole. One uses the middle pole as a
temporary resting place for the disks. However it is allowed for a larger disk to
be on top of a smaller one. For example if we have three disks then the moves
are
86 Problems and Solutions
(i) Write a C++ program using recursion to implement the Tower of Hanoi.
(ii) Write a C++ program using the stack class of the standard template li-
braray to implement the Tower of Hanoi.
Problem 13. Using the Verylong class of SymbolicC++ and the complex
class (of STL) that finds positive integer solutions (a, b, c) of the equation
c = (a + bi)3 107i
where i2 = 1.
Problem 14. Let i = 1. Calculate ii . Use the complex class of the
standard template library of C++ to calculate ii . Discuss.
Chapter 14
Particle Swarm
Optimization
87
88 Problems and Solutions
points of the objective function. As such, gradually over many iterations, the
particles go to the target (the extremum point of the objective function).
The algorithm for determining the maximum of a function f (x) (with x an n
1) Initialize the number of particles N , the search intervals for each dimension
(ai , bi ), i = 1, . . . , n (n being the dimension of the search space), the search
precision for each dimension i , the maximum number of iterations imax .
Initialize the positions of the particles xj (0) = rand(), j = 1, . . . , N randomly
in the search domain.
Initialize the speeds of the particles vj (0) = 0, j = 1, . . . , N .
Initialize the individual best positions of the particles xbest,j (0) = xj (0), j =
1, . . . , N .
Initialize the iteration count k = 0.
2) Check the stop conditions: the diameter of the swarm in each dimension is
less then the dimensions precision i , or the maximum number of iterations imax
was reached. If yes then terminate else continue to step 3).
3) Calculate the values of the function f (x) in the current positions of the par-
ticles, f (xj (k)), j = 1, . . . , N . Update the values of the best individual points
for each particle xbest,j (k), j = 1, . . . , N and the value of the global best point
xbest (k). Continue to 4).
where max is a maximum value and min is a minimum value, typically max =
0.9 and min = 0.4. Continue to 5).
5) Update the particles positions by applying the formula:
xj (k) = xj (k 1) + vj (k), j = 1, . . . , N
f (x) = x2 + 2x + 11, 2 x 2
Problem 2. Minimize
by applying the Particle Swarm Optimization (PSO) method. The required pre-
cision is 103 .
Problem 3. Find the global minimum of the De Jongs function (or sphere
model)
n
X
f (x) = x2i , n 2
i=1
selected population vectors to produce the trial vectors. Assume that we pro-
duce the trial vector with index 0, u0 . DE selects randomly two distinct vectors
xr1 and xr2 from the population and adds the scaled perturbation xr1 xr2 to
a third vector also randomly selected from the population xr3 , distinct from the
first two vectors. The procedure is repeated in order to generate all the set of
trial vectors u0 , u1 , . . . , uNp . In the selection stage, each trial vector competes
against the vector in the population vectors with the same index. The vector
with the lower objective function value is selected as a member of the next gen-
eration. The survivors of the Np pairwise competitions become parents for the
next generation in the evolutionary cycle. The evolutionary cycles are repeated
until a termination criteria is meet, for example the diameter of the population
becomes less than a small limit value or a maximum number of population
generations were generared.
The more detailed algorithm for determining the global minimum of a function
The crossover probability, Cr [0, 1), is a user-defined value that controls the
fraction of parameter values that are copied from the mutant. To determine
which source contributes a given parameter, uniform crossover compares Cr to
the output of a uniform random number generator. If the random number is less
than or equal to Cr , the trial vector component is inherited from the mutant
(k) (k)
vi ; otherwise, the trial vector component is copied from the vector, xi . In
addition, the trial vector component with randomly chosen index, jrand , is taken
(k)
from the mutant to ensure that the trial vector does not duplicate xi . Because
of this additional demand, Cr only approximates the true probability, pCr , that
a trial parameter will be inherited from the mutant.
(k)
4) Selection - if the trial vector, ui , has an equal or lower objective function
(k)
value than that of its target vector, xi , it replaces the target vector in the next
generation; otherwise, the target retains its place in the population for at least
one more generation:
(
(k) (k) (k)
(k) ui if f (ui ) < f (xi )
xi = (k) i = 1, . . . , Np
xi otherwise
By comparing each trial vector with the target vector from which it inherits pa-
rameters, DE more tightly integrates recombination and selection than do other
Evolutionary Algorithms.
5) Termination - check the termination conditions: the diameter of the pop-
ulation is less then the preset precision , or the maximum preset number of
generations imax was reached. If yes then terminate, else increment the itera-
tion count k and go to 2).
Steeb W.-H.
The Nonlinear Workbook: Chaos, Fractals, Cellular Automata, Neural Networks,
Genetic Algorithm, Gene Expression Programming, Wavelets, Fuzzy Logic, fifth
edition
World Scientific Publishing, Singapore 2011
ISBN 978-981-4335-77-5
http://www.worldscibooks.com/chaos/8050.html
Steeb W.-H.,
Mathematical Tools in Signal Processing with C++ and Java Simulations
World Scientific Publishing, Singapore 2005
ISBN 981 256 500 0
http://www.worldscibooks.com/engineering/5939.html
93
Index
94
Index 95
Resultant, 48
Shannon entropy, 74
Shuffle product, 75
Sinc function, 4
Spiral map, 85
Stirling number, 40
Toeplitz matrix, 43
Tridiagonal form, 47
Wavelet theory, 77