Computational Physics Lab 1

Computational Errors


Part 1. Exploring Floating Point Numbers on Your Computer

Write a python program which determines the largest float, the smallest positive float, and the machine precision (python floats are 64-bit numbers). Compare the results with your expectations from IEEE 754.

Part 2. Avoiding Subtractive Cancellation

The standard way to solve the quadratic equation

a x2 + b x + c = 0

taught in high schools looks like this:



Show that this formula results in a subtractive cancellation in case one of the equation roots is close to 0 and the other one isn't. There is a better way to calculate the solutions which avoids the problem:




where sgn(b) is the sign function and the case b = 0 should be handled separately. Write a python module which solves the quadratic equation in two different ways (with and without the cancellation). Compare the results for some equations.

Part 3. Avoiding Excessive Error Amplification

One possible way to determine the angle between two vectors is to use the property of the scalar product:



Then the angle can be determined as

Show that a translation of this formula into computer code results in an algorithm which exhibits strong error amplification in case the vectors are nearly parallel or nearly antiparallel. Can you come up with a better way to calculate the angle?

Part 4. Convergence Does Not Mean Correctness

The program harmonic_series.cc attempts to sum up the harmonic series using single-precision floating point numbers (this program is written in C++ for speed). Can you predict the result before actually running the program? Note that single-precision floating point numbers look just like the double precision numbers except that they use 23 bits for the mantissa and 8 bits for the exponent (with the sign bit this makes 32 bits total). The exponent bias is -127.

In order to compile and run the program, download the file and then run

g++ -o harmonic_series harmonic_series.cc
./harmonic_series