Why am I losing accuracy when converting float32 to float64?

Converting the number of float32 to precision float64 is lost in Go. For example, converting 359.9 to float64 produces 359.8999938964844. If float32 can be accurately saved, why does float64 lose precision?

Code example:

package main import ( "fmt" ) func main() { var a float32 = 359.9 fmt.Println(a) fmt.Println(float64(a)) } 

Try on the Playground

+5
source share
2 answers

You never lose accuracy when converting from float (i.e. float32) to double (float64). The former should be a subset of the latter.

This has more to do with the default accuracy of the output formatter.

Nearest IEEE754 float up to 359.9

 359.899993896484375 

Nearest IEEE754 double to 359.9

 359.8999999999999772626324556767940521240234375 

Nearest IEEE754 double to 359.899993896484375

 359.899993896484375 

(i.e. the same thing, due to the subset rule that I already mentioned).

So you can see that float64(a) matches float64(359.899993896484375) , which is 359.899993896484375 . This explains the output, although your formatter rounds the last 2 digits.

+6
source

This helped me understand @FaceyMcFaceFace's answer:

 var a float32 = math.Pi fmt.Println(a) fmt.Println(float64(a)) fmt.Println(float64(math.Pi)) 3.1415927 3.1415927410125732 3.141592653589793 

https://play.golang.org/p/-bAQLqjlLG

+3
source

All Articles