Advanced Octave A19 — Numerical errors and stability
Advanced GNU Octave with GX-TXT · Module 04
Two algebraic equivalent expressions can produce different results in mobile comma. The difference is not necessarily an error of the program: it can be born from the rounding of the intermediate results.
Objectives and prerequisites
The introductory course introduced the numerical calculation. Here we observe the loss of a small contribution when it is added to a very large one, both in Octave and using a numerical operation of the Bridge GX-TXT. The test uses GX-TXT dev112-P011-bis and GNU Octave 9.4.0.
Change the order of calculations
Import cancellazione.m, save it in the Session and run it in the Runner.
We have a = 10¹⁶, b = −10¹⁶ and c = 1. The exact mathematical result of the sum is one. The script calculates both (a+c)+b and (a+b)+c, then repeats the first order with two NUMERIC_API_v1/array_binary calls.
(a+c)+b produces 0, while (a+b)+c produces 1. In the arithmetics used, add 1 to 10¹⁶ does not retain that contribution in the intermediate result; the subsequent sum with −10¹⁶ leaves zero. In the second order the two large numbers are erased before adding one.
The Bridge also returns zero for the first order: passing a calculation to a service does not automatically delete the limits of the numerical representation. The print with %.0f shows the resulting wholes, but change the number of digits displayed does not restore an already lost contribution.
From demonstration to analysis
Reordering terms can help in a known case, but it is not a universal solution. For long sums, subtractions between close quantities and poorly conditioned problems, choose appropriate methods, control scales and units, compare with a reference solution when possible and evaluate the error with respect to scientific needs.
Distinguish absolute and relative error is essential: an error of a unit can be negligible compared to 10¹⁶, but decisive when the expected result is 1.
Exercise
- What is the exact mathematical result of
a+b+c? - Why do the two observed groupings return different numbers?
- Increase the figures shown by
fprintfautomatically recovers the lost value?
Worked solution
- One.
- The first grouping rounds the intermediate result and loses the small contribution; in the second the big terms cancel first.
- No: formatting changes textual representation, not the numerical value already calculated.
Other steps of this project
- Advanced Octave A75 — Dynamical systems in phase space
- Advanced Octave A81 — Geography of the waves and a 3D surface
- Advanced Octave A82 — Age, sex and demographic inequalities
- Advanced Octave A83 — All-cause mortality, certified COVID deaths and surveillance
- Advanced Octave A84 — A reproducible public account
- Advanced Octave A73 — Optimization landscapes and 3D trajectories