Order of evaluation and floating point numbers

March 25, 2024

Today I’ll be live streaming again! This time, picking up where we left off last week, and adding another feature to my new Go code rewriter and simplifier. Join me!


Order of Evaluation

Floating-point operations within a single expression are evaluated according to the associativity of the operators. Explicit parentheses affect the evaluation by overriding the default associativity. In the expression x + (y + z) the addition y + z is performed before adding x.

Why bother spelling this out? Isn’t x + y + z the same as (x + y) + z the same as x + (y + z)?

Well, in mathematics, where values are precise, yes, it is. But floating point numbers are approximations, and not exact. At least not always.

Consider this simple program:

x := 0.1
y := 0.2
z := 0.3
fmt.Println(x + y + z)
fmt.Println((x + y) + z)
fmt.Println(x + (y + z))

The first two Println lines output the same value, as one might expect, since (x + y) + z follows the default order of evaluation. But the third output differs, since we override that default order. What is the output of these three lines?

0.6000000000000001
0.6000000000000001
0.6

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe