Академический Документы
Профессиональный Документы
Культура Документы
scientific Computing
Part I
This portfolio is by
Sifiso Samson Thwala
Foreword
IT is a vast field that overwhelms me and my fellow acquaintances hence we are actually studying,
researching and trying our level best to develop IT as much as possible. IT ranges from (fundamentally)
bitwise operations used in machine level to number manipulation used in computational applications to
combinatorial problems leading to the ever so vast study of AI (Artificial intelligence) to matrix calculus
which is the basis of graphics and graphical user interfaced applications, etc... Scientific computing -
which was highly used in this portfolio and most, if not all, of my projects – is a collection of tools,
techniques and theories required to develop and solve mathematical models in science and engineering on a
computer, bridging the gap of the theoretical side of academics and the work experience of professionals to
produce a well thought after solution to common and even critically rare and unconsidered problems.
It as been my life’s work to ponder ideas and research in this industry, so I hope the few examples I have
compiled here for illustration purposes offer more insight on IT itself than praise any persona, for the
discipline itself is the future and let man give his all to it, in order of it to grow.
The basis of the code provided will be written in this documentation, for background knowledge into the
problems solved in the dot CPP of dot JAVA files accompanying thin document. All implementations and
testing of the C++ programs have been done of gcc 3.3, DevC++ and Microsoft Visual Studio.NET, while
for java I used version 1.6.0 (jdk1.6.0), May you not have any problems running the executable file given.
Should you need to recompile, you may, provided that the original file are not modified directly.
© All rights are reserved by the University of Johannesburg, meaning that this documentation and/or the underlying
code may not be reproduced in any form or by any means, electronic or mechanical, including photocopying,
recording or any information storage and retrieval system now known or to be inverted, without written permission
from the author
Contents
Security
Checksum
Cyclic Redundancy Checks
Functionality
Exclusive OR function
Baeza-Yates-Gonnet
Let’s play
The Maze
Sudoku
Practical
Finite State Machines
Dictionary Word Processor
ChatRoom
Mathematics
Eigenvalues and Eigenvectors
Matrix class in C#
Graphics
Grey Picture
GIMP
Bézier curve
Harmonic interpolation
Bibliography
Checksum
checksum.cpp
A checksum can be used to determine if errors occurred in transmission of data. It is widely used in the
internet by several protocols. The checksum works as a liner and cyclic code does yet it is based on the
concept of redundancy, several protocols within the internet model still primarily use it for error detect.
The checksum is based on a 32-bit checksum algorithm that simply adds all data in the transmission as if it
were 32-bit quantities, i.e. we read 4 bytes each and the resulting 32-but quantities, when the checksum
overflows, and the overflow bit is added to the checksum.
• The underlying Checksum.cpp code will illustrate: Checksum computation of some data and
provide options for comparing the checksum to a given value.
ii) Pitfall: If we look at the checksum it is clear that any difference in two sequences of 32-bit
values that is not a multiple of 2 32 in total will result in a different checksum. This allows us
to detect all errors that do not produce a difference in the sum of precisely 2 32 =
4294967296. The checksum in this example is further improved by the addition of the carry
bit. The addition of the carry bit will prevent multiples of 4294967296 from being detected as
a no error condition. So now all errors must result in a net increase of zero in the sum if they
are to go undetected, i.e., some values must decrease and others increase to get a net result of
zero difference over the sum.
Cyclic
Redundancy
Checks
CRC32.cpp
Cyclic redundancy checks provide a better means of checking data for errors (well it’s the closest one
before to brute force).Cyclic Codes are special linear block codes with one extra property, in cyclic code, if
a code word is cyclically shifted (rotated), the result is another code word and the a Cyclic redundancy
check is an instance of cyclic code.
Now the origins of this function dates far back from the evolutions of logic from mathematics and has been
a tool ever since. Although the precise date of the XOR function’s origins is undetermined, the modern use
of it fascinated me because it’s an essential tool to modern Structures such as Graphics.
sets the paint mode of this Graphics context to alternate between this Graphics context’s current colour and
the new specified colour.
The maze is an illustration of recursion; a blood hound implementation is given here which find the
possible solution to the maze a maze which could be randomly generated but for illustration purses hard
coding will do the trick. The aim of the maze is to move from position (0, 0) – top left corner – to the
position (m – 1, n – 1) – bottom right corner following the path’s of 1’s. We can only move to the right,
left, down and up but not diagonal. Write a java program using recursion that find out whether or not
there’s a solution and if so provide a solution which is denoted as a path of 5’s.
This common recursive problem that occurs in many disciplines but the most exciting one is within infinite
state machine especially severs and other none terminating applications and machinery.
Sudoku
Sudoku.cpp
Sudoku is a numerical puzzle. The puzzle consists of 9x9 squares arranged in a grid. This grid is further
subdivided into 3x3 squares of size 3x3. Some numbers are initially placed on the grid. To solve the puzzle,
a number between 1 and 9 (inclusive) must be selected for each square that is empty so that:
1. No number is duplicated in any row.
2. No number is duplicated in any column.
3. No number is duplicated in any of the 3x3 subgrids.
This a program allows a user to specify and solve a sudoku puzzle. Initially the 9x9 grid is empty, the user
types in the numbers that are given for the puzzle. Thereafter, the user types in the numbers that he/she has
computed to solve the puzzle at each stage.
The program displays the puzzle on the screen, with the entered numbers after each new number is entered.
Note: The user can choose to enter a new number at any position he/she chooses, as long as there is
no number there already.
After all squares have been filled with a number, I check that the puzzle has a solution by making sure that
the above constraints are satisfied. Note: there may be many, or perhaps no solutions to the puzzle.
Finite
State
Machines
machine.cpp
This is a skeleton design of a Mealy machine to represent a vending machine which provides a carbonated
drink for R2,50. The machine accepts 50c, R1 and R2 coins. The symbol number output by the machine is
interpreted a change (in cents) for the customer. The symbol ‘c’ output by the machine is interpreted as the
output of the carbonated drink. We allow null output, i.e., output which does not actually appears (empty
string). Thus the output ‘symbols’ we could expect are the strings:
For the illustration I use the states to indicate how many 50c the vending machine has received. In other
words S0 represents 0c, S50 represents 50c and so on. The following transition table describes the machine.
S200 50c C S0
S200 R1 C50 S0
S200 R2 C150 S0
Dictionary Word Processor
SpellChecker.cpp
The program is a spellchecker program. The program takes parameters on the command line to specify the
file to be checked and optionally the dictionary file. The dictionary file is read in and stored in memory.
The program reads the file to be spellchecked word for word, and sees if each word is in the dictionary file.
If the file has a spelling error an option to change the word (in which case the file is modified). The modi-
fied file is written to a new file.
• You must use a binary search algorithm to check if the word is in the dictionary.
• Make suggestions when a spelling mistake has been made.
• Ignore the case of words. (Hint: use to upper)
• Ignore punctuation.
The spell checker Challenge is a special case that is continuously and new commonly used way of alternat-
ive words. Instead of lexicon order of the alphabet it also detects meaning, so it detects a couple of letters
of cases. Like ‘impottant’ word be important
ChatRoom
ChatClient.java
ChatRoomServer.java
etc
This program implement a basic electronic chatroom application that employs a multi threaded server.
Client:
The client is implemented as a GUI that can send and receive messages until it sends the string 'Bye'.
A separate thread receives messages from the server and adds them cumulatively to a text area. The thread:
• Accept the user's chatroom nickname via an input dialogue box
• Send this name to the server.
• All other messages are sent via a text area with an associated button.
As a simplification, it is assumed that no two clients will use the same nickname
Server:
The chat server is multi threaded and must be able to:
• Broadcasts each message it receives to all the connected clients.
• Maintain a dynamic list of Socket references associated with those clients. Though you could use
an array to hold the list, the use of a Vector object would be much more realistic.
Eigenvalues
and
Eigenvectors
Eigenvalues.cpp
The German adjective eigen means “own” or “characteristic of”, eigenvalues and eigenvectors are
characteristic of a matrix in the sense that they contain important information about the nature of the
matrix, To find eigenvalues and eigenvectors of a symmetrical matrix over R one often uses the Jacobi
method. It consists of a sequence of orthogonal similarity transformation of the form
q pp = q rr = cosθ , qii = 1 → i ≠ p, r
q pr = − q rp = − sin θ , qip = q pi = qir = q ri = 0 → i ≠ p, r
qij = 0 → i ≠ p, r ∩ j ≠ pr.
The idea of the Jacobi method is to try to zero off diagonals elements by a series of plane rotations.
Matrix
This is a class that was created purely to be generic. IT is one of my ventures of studying C# and its syntax.
The Matrix class is simple textbook work – in fact I just took my old text book from the shelf - and merely
spans in the regular and generic cases of a typical matrix.
The UML diagram of the class:
Matrix
- Mat : double [ , ]
+ <<constructor>> Matrix()
+ Clone() : Object
+ Equals( in b : Object) : boolean
+ <<operator +>> Matrix ( a : Matrix, b : Matrix )
+ <<operator ->> Matrix ( a : Matrix, b : Matrix )
+ <<operator *>> Matrix ( a : Matrix, b : Matrix )
+ <<operator *>> Matrix ( a : Matrix, b : Vector )
+ Transpose() : Matrix
+ Translate( v : Vector ) : Matrix
+ Scale ( s : double ) : Matrix
+ Scale ( sx : double, sy : double, sz :double ) : Matrix
+ Rotate ( axis : Vector, angle : double ) : Matrix
+ Projection ( n : double, f : double , t : double, b : double, l : double, r : double ) : Matrix
+ ToString() : string
Grey Picture
Computer graphics program seldom take the structure and functioning of the eye into account. If they do,
the results usually take a very long time to produce.
One of the peculiarities of the eye (or camera) is focal length. A certain distance in the scene remains in fo-
cus, whereas closer (or further) objects appear to be blurred. A typical ray tracer program produces crystal
clear images for all distances. To make the result realistic, we would like to simulate the focal length or
depth of field. We thus need to be able to read images stored in binary format. The images provided for this
practical are gray files. The format of the gray file is as follows:
The values in the image indicate the intensity with 0 being black and 255 white. The values in between
specify shades of gray. You are also given a depth image of exactly the same size and format.
However, the values are interpreted as:
Load both an image and its depth map into separate two dimensional dynamic arrays. Now, apply a Gaus-
sian filter:
1 2 2 2
G ( x, y ) = e − (( x − col ) + ( y − row) ) /( 2 r ))
2π r 2
For each pixel, we calculate the value r (given below) and then use a nested for loop to iterate from 3r rows
before to 3r rows afterward, and likewise for the columns. Multiply the Gaussian function by the intensity
at that position in the image and add the results together. Be sure to check whether the pixels are in bounds,
x and y refers to the pixel under consideration and G can be used to calculate the relative importance of the
pixel. We thus compute
row + 3 r col + 3 r
newimage[ row][col ] = ∑ ∑ G ( x, y )image[ y ][ x ]
y = row − 3 r x = col − 3 r
I used floating points to calculate the value and typecast back to an unsigned char afterward. The radius r is
determined by the focal length f,
r = | d − f | / 50
Where d = depth[row][col] is the depth value stored at the pixel. Make sure that r is at least 0.5.
For example, consider the image and depth map of a castle:
The name of the image and depth map, as well as focal length must be passed through on the command
line. The resulting image must be written to file in gray format. A program will be included to view gray
files, and example data will be provided.
Images and scene files are provided by Gilles Tran.
GIMP
A computer image is made up of tiny elements called pixels (picture elements). Each element is composed
of differing values of the colours red, green and blue called RGB values. These are often represented as a
set of three numbers ranging from 0-255. For example 0 means that none of that particular colour is includ-
ed and 255 means that all of that colour component is included. The colour Red for example would be rep-
resented as 255 0 0, Blue as 0 0 255 and Green as 0 255 0
Christian Faur[1] is an artist who has devised a mapping between colours and characters in the Latin alpha-
bet where the most striking colours (as measured by human perception tests) are mapped onto the most fre-
quently used letters in the English language.
Mr. Faur’s mapping is as follows (used with the permission of the artist):
The portable pixel map[2] (.ppm) file format is a very simple text-based file format for representing graphi-
cal images. We will be using a simplified* version of the format as follows:
P3
#generated by <executable name>
Image-width image-height
Max-value-for-rgb
R G B R G B R G B…
R G B R G B R G B…
R G B R G B R G B…
.
*our simplified version will ignore the 70 character line limit so that one line of our image is equal to one
line of RGB values in the PPM file.
In order to view one of our PPM files you will need to use an imaging tool a little more sophisticated than
MS-Paint. I highly recommend using The GIMP[3] (GNU Image Manipulation Program) which is both
open source and extremely capable. An example PPM file encoding the string “Hello World” is available
under the additional files section of this practical. The example file would appear visually as follows when
loaded into the GIMP.
[1] http://www.christianfaur.com/conceptual/colorAlphabet/index.html
[2] http://netpbm.sourceforge.net/doc/ppm.html
[3] http://www.gimp.org/
Bézier curve
Bezier.java
A Bézier curve B(t) of degree n is defined by a set of control points pi for i = 0,1,..., n as follows:
n
B (t ) = ∑
i= 0
pi Bi ,n (t )
∑
i= 0
Bi , n (t ) = 1
We have Bi , n (t ) ≥ 0 to every 0 ≤ t ≤ 1 . The properties imply that the Bézier curves are affine invariant
and that the curve lies entity in the convex hull of the control points defining the curve. We find that
B (0) = p0 and that B (1) = pn . Thus, the Bézier curve interpolates the end points, we find that
dB dB
(0) = n( p1 − p0 ) , (1) = n( pn − pn − 1 )
dt dt
Thus the tangents at the end points of the curve are easily computed. This allows us to construct piecewise
smooth C 1orG1 curve out of Bézier curves by setting n p ( p1 − p0 ) = cnq (qn − qn − 1 ) for a curve
nq
Q(t ) = ∑i= 0
qi Bi , n (t )
Followed by a curve
np
P (t ) = ∑
i= 0
pi Bi , n (t )
The projection matrix p j can be expressed using U k . Since Pj Pk = 0 for j ≠ k and Pj2 = Pj we find:
n− 1
Uk = ∑
j= 0
λ j Pj k = 1,2,..., n.
Thus, we calculated the Fourier transform of the projection matrices. For k = n we have U n = I n and the
completeness relation:
n− 1
In = ∑j= 0
Pj
(λ jk ) is given by 1 n (λ ) . Thus
− jk
The inverse of the matrix
n− 1
n∑
Pj = 1 λ − jkU k , j = 0,1,..., n − 1.
k= 0
We apply the permutation in such a way that we can continuously interpolate between the points of the
polygon. We embed the matrices U k into a real Lie group. Thus we have to consider the cases n = 2m + 1
and n = 2m, where m is a positive integer. In the second case we have λ 0 = 1 and λ m = − 1 . Furthermore,
we define P− j := Pn − 1. The projection matrices are therefore real. We consider first case n = 2m +1. we
obtain by replacing k by nt , t ∈ [ 0,1]
m
~
U (t ) = P0 + ∑j= 1
(e 2π ijt Pj + e − 2π ijt P− j ), t ∈ ℜ
~ ~ ~ ~ ~
The unitary matrices U (t ) are 1-periodic, i.e. U (t + 1) = U (t ) . Thus U (t + 1) = U (t ) and
~ ~
U ( k / n) = U k fork = 0,1,..., n − 1 . Owing to the previous, we can write U (t ) as:
n− 1 m
~
n∑ ∑
U (t ) = 1 (1 + (e 2π ij (t − k / n ) + e − 2π ij (t − k / n ) ))U k
k=1 j= 1
m
1
We define: δ k (t ) ≡ δ (t − k / n):=
n
(1 + ∑
j= 1
(e 2π ij (t − k / n ) + e 2π ij (t − k / n ) ))
n− 1 n− 1
We have the properties: ∑
k= 0
δ k (t ) = 1 ∑
k= 0
δ k2 (t ) = 1.
thus the functions δ k (t ) and δ k (t ) provide a partition of unity and the harmonic interpolation is affine
2
invariant. Now let x = ( x0 , x1 ,..., xn − 1 ) be the vector which describes the polygon. Then
T
n− 1
~
X (t ) = U (t ) X = = ∑
k= 0
δ (t − k / n)U k X
The curve which describes our closed smooth curve is given by:
n− 1 n− 1
X l (t ) = ∑
k= 0
δ (t − k / n) X k + l = ∑
k = .0
δ (t + l / n − (k + l ) / n) X k + l = X 0 (t + l / n)
Where ( k + l ) is calculated mod n. Hence, for all l it represents the same curve and we can write:
n− 1
X (t ) = ∑
k= 0
δ (t − k / n) X k , t ∈ [0,1]
Thus this curve interpolates the points of the given polygon smoothly. We consider now the case n = 2m.
for this case we may write:
m− 1
U k = P0 + (− 1) k Pm + ∑j= 1
(λ jk Pj + λ − jk P− j ).
If we replace the discrete variable k by the real variable t, we find the factor (− 1) k ≡ e π it The other terms
are real. Thus, t the Lie group we could find is not real and therefore cannot be used directly for the
harmonic interpolation in computer graphics. Since the function U(t) will be continuous in the complex
domain and go through the points of the polygon. A similar calculation as described for the case n = 2m +1
given above yields (t ∈ [0,1])
n− 1 n− 1 n− 1
~
n∑ n∑ ∑
U (t ) = 1 cos(π (nt − k ))U k + 1 sin(π (nt − k ))U k + ξ k (t )U k
k= 0 k= 0 k= 0
sin(π (nt − k ))
Where: ξ (t ) := , ξ (t ) := ξ (t − k / n)
n sin(π t )
Thus, our smooth curve in the even case which goes through all the points of the polygon is:
n− 1
X (t ) = ∑ k= 0
( 1 cos(π (nt − k )) + ξ k (t )) X k
n
`Most calculations and deductions were guided by Prof. A hardy and Prof.WH Steeb
The java applet and application draw the harmonic interpolation of a polygon.
Bibliography
David Poole
Linear Algebra a modern introduction second edition
Thomson BROOKS/COLE (2006)
Séroul R.
Programming for mathematicians
Springer Verlag, Belin (1991)
Bäck T.
Evolutionary Algorithms in Theory and Practice
Oxford University Press, Oxford (1996)
Baase S.
Computer algorithms, Second Edition
Addison-Wesley, Reading, Massechusetts(1988)