Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 57 / 68

Watch out for floating-point error

This lesson covers floating-point error in R, with the aim of understanding why decimal arithmetic can give surprising results.

Computers hold decimals in binary, so even a simple calculation such as 0.1 + 0.2 may not come out exactly 0.3. Displayed, the error shows; compared, you get FALSE.

The sample code shows that cat(0.1 + 0.2) prints a value carrying an error (sometimes rounded for display) and that 0.1 + 0.2 == 0.3 comes back FALSE. This happens in most languages that use floating point.

A common early stumble is comparing decimals directly with == and not getting the expected result. In R the safe approach is all.equal(), which compares within a tolerance.

In professional work, accumulated rounding error in statistical calculation needs care, so understanding the behaviour matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)