Chapter 4
Numerical Errors and Uncertainty in Computation
This program contains three short experiments on floating-point representation and precision, cancellation, and order of summation. Each version is a single file and prints its results on screen. Matching implementations are provided in MATLAB, Python, C++, and Fortran. The Python version requires NumPy for single precision; the MATLAB version requires no additional packages.
Run the program, inspect its output, and change the numbers to explore the behavior. Many digits are printed to expose rounding effects; extra displayed digits do not increase accuracy. The Chapter 4 resources explain the expected results and suggest further comparisons.
| Program | MATLAB | Python | C++ | Fortran |
|---|---|---|---|---|
| Floating-point experiments Compares single and double precision, two equivalent formulas affected differently by cancellation, and two orders of summation. | Download | Download | Download | Download |
Running the programs
From the folder containing the downloaded source file:
- MATLAB: enter
ch04_roundoff. - Python: run
python3 ch04_roundoff.py. - C++: compile with
g++ -std=c++11 ch04_roundoff.cpp -o ch04_roundoff, then run./ch04_roundoff. - Fortran: compile with
gfortran ch04_roundoff.f95 -o ch04_roundoff, then run./ch04_roundoff.
On Windows, compile with -o ch04_roundoff.exe and run
.\ch04_roundoff.exe in PowerShell. The Python command is
commonly python ch04_roundoff.py or
py ch04_roundoff.py, depending on your installation.
The examples assume ordinary IEEE single and double precision with
rounding to nearest. Use normal compiler settings without options
such as -ffast-math, which can rearrange arithmetic.
Extended-precision intermediate calculations, such as those on some
older x87 builds, can change the displayed results.