-3

The StackOverflow answer here is very complex for a beginner like me.

Executing the following line of code in Golang results into 1

fmt.Println(1.0/3.0 + 1.0/3.0 + 1.0/3.0)

According to my knowledge, 1.0/3.0 results into 0.3333333... which cannot be stored accurately then what causes this result.

I am not acquainted with low things like how a processor or CPU executes a particular instruction. Can anyone give me a simple answer?

1 Answers1

2

According to The Go Programming Language Specification, “Constant expressions are always evaluated exactly…” This means the compiler (or other implementation) is required to do full real-number arithmetic to the extent required to evaluate a constant expression. Thus 1.0/3.0 + 1.0/3.0 + 1.0/3.0 is evaluated as ⅓ + ⅓ + ⅓, which is of course 1.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312