
When I show my students that, contrary to expectations, the sine of pi in MATLAB or Python is not 0 but approximately 1.2246e-16, I usually see looks of astonishment on their faces. However, this result is not incorrect; rather, it follows the rules of floating-point arithmetic.
On a computer, we describe numbers with a finite (e.g., 32 or 64) total number of zeros and ones, that is, with the so-called binary system. The total number of representable numbers is therefore finite, in contrast to the total number of real numbers. In a 64-bit system, there are 2e64 (or ~1.8447e19) different numbers. These floating point numbers are arranged such that the density is greatest around zero and decreases in the direction of minus infinity and plus infinity in order to support a trade-off between precision and range.
The value pi cannot be represented exactly in binary, so the stored value is actually rounded to the nearest double-precision floating-point number. And the sine of this approximate value of pi is, consequently,
format long pi ans = 3.14159265358979 sin(pi) ans = 1.224646799147353e-16
in MATLAB and
import numpy as np np.pi 3.141592653589793 np.sin(np.pi) np.float64(1.2246467991473532e-16)
in Python. Once again, this is not an incorrect result, but the correct result according to floating-point arithmetic. You should be aware of this problem—and many similar ones—and program accordingly. It is easy to see how the program could run incorrectly if you use sin(pi)=0 as a condition in a WHILE loop; instead you should use abs(sin(pi))<1e-15 for example. Floating-point numbers require careful attention to prevent incorrect calculations in MATLAB and Python.
I wrote about this in an earlier post that included examples for MATLAB. You can find an updated version, covering both MATLAB and Python, in the latest editions of my books MATLAB Recipes for Earth Sciences, 6th Edition (2025) and Python Recipes for Earth Sciences, 2nd Edition (2024). And of course, we will also discuss this issue and ways to resolve errors in the upcoming MATLAB and Python course (14–18 September 2026).
References
Trauth, M.H. (2025) MATLAB Recipes for Earth Sciences – Sixth Edition. Springer International Publishing, 567 p, https://doi.org/10.1007/978-3-031-57949-3.
Trauth, M.H. (2024) Python Recipes for Earth Sciences – Second Edition. Springer International Publishing, 491 p., https://doi.org/10.1007/978-3-031-56906-7.
