go - Why am I losing precision while converting float32 to float64? -
while converting float32 number float64 precision being lost in go. example converting 359.9 float64 produces 359.8999938964844. if float32 can stored precisely why float64 losing precision?
sample code:
package main import ( "fmt" ) func main() { var float32 = 359.9 fmt.println(a) fmt.println(float64(a)) }
try on playground
you never lose precision when converting float
(i.e. float32) double
(float64). former must subset of latter.
it's more defaulting precision of output formatter.
the nearest ieee754 float
359.9
359.899993896484375
the nearest ieee754 double
359.9
359.8999999999999772626324556767940521240234375
the nearest ieee754 double
359.899993896484375 is
359.899993896484375
(i.e. same; due subsetting rule i've mentioned).
so can see float64(a)
same float64(359.899993896484375)
359.899993896484375
. explains output, although formatter rounding off final 2 digits.
Comments
Post a Comment