On Sat Apr 9, 2022 at 3:56 PM CEST, 'Jack Li' via golang-nuts wrote:
> Why literal operation is exact, variable is not?
>
> fmt.Println(0.1 + 0.2) // 0.3 exactly
> fmt.Println(x + y) // 0.30000000000000004
>

Both aren't exact because floats can't represent 0.3 exactly, they
differ because literals and constants expressions have arbitrary
precision (http://golang.org/ref/spec/#Constants), so "0.1" and "0.2"
in "0.1 + 0.2" are exact, then when the exact "0.3" result is
converted to a float64 it becomes the closest possible, You can check
this if you ask to print with more precision

x, y := 0.1, 0.2
fmt.Printf("%.17f...\n", 0.1+0.2) // 0.29999999999999999...
fmt.Printf("%.17f...\n", x+y)     // 0.30000000000000004...

https://go.dev/play/p/2qSfoCZGaD6

-w

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CJ6VDO2DK4XB.3VDUG02EUZ58S%40pampas.

Reply via email to