Why does 0.1 + 0.2 get 0.3 on Google Go?

As long as a floating point is used, 0.1 cannot be accurately represented in memory, so we know that this value usually goes up to 0.10000000000000004.

But when using, go to Appendix 0.1 and 0.2. I get 0.3.

fmt.Println(0.1 + 0.2) // Output : 0.3 

Why did 0.3 come out instead of 0.30000000000000004?

+5
source share
1 answer

This is because when you print it (for example, using fmt ), the print function is already rounded to a certain number of fraction digits.

See this example:

 const ca, cb = 0.1, 0.2 fmt.Println(ca + cb) fmt.Printf("%.20f\n", ca+cb) var a, b float64 = 0.1, 0.2 fmt.Println(a + b) fmt.Printf("%.20f\n", a+b) 

Conclusion (try on the Go Playground ):

 0.3 0.29999999999999998890 0.30000000000000004 0.30000000000000004441 

We used constants at first , as this was different from using (mutable) values โ€‹โ€‹of type float64 . Numeric constants are exact values โ€‹โ€‹of arbitrary precision and do not overflow.

But when printing the result of ca+cb , the constant value must be converted to a variable, typed value, which can be passed to fmt.Println() . This value will be of type float64 , which cannot represent exactly 0.3 . But fmt.Println() will round it to 16 digits of a digit, which will be 0.3 . But when we explicitly declare that we want it to be displayed with 20 digits, we will see that this is not accurate. Note that only 0.3 will be converted to float64 , because constant arithmetic 0.1+0.2 will be evaluated by the compiler (at compile time).

Then we started with variables like float64 , and it is not surprising that the output was not 0.3 exactly, but this time even with rounding by default we got a result different from 0.3 . The reason for this is that in the first case (constants) it was converted 0.3 , but this time both 0.1 and 0.2 were converted to float64 , neither of which is accurate and adding them in an amount having a greater distance from 0.3 is enough great to make the "visual appearance" with the default rounding of the fmt package.

Browse related / current questions + answers to learn more about the topic:

Why do these two float64 have different meanings?

How does Go do arithmetic on constants?

Golang converts float64 to int error

Is compiler pricing different for constant expression and other expression

Why is adding 0.1 several times without loss?

Golan round to the nearest 0.05

Go: Convert float64 to int with multiplier

+5
source

Source: https://habr.com/ru/post/1264056/


All Articles