0

When I print out the maximum values for uint64, float32 and float64 it seems as though a float should accommodate a uint64. However, I've tried a number of conversions and large uint64 numbers do not convert accurately. Am I doing something incorrectly? Or am I misunderstanding the documentation and language constraints?

fmt.Printf("Max unit64 value = %d\n", uint64(math.MaxUint64))
fmt.Printf("Max float32 value = %f\n", float32(math.MaxFloat32))
fmt.Printf("Max float64 value = %f\n", float64(math.MaxFloat64))

var ui64 uint64
ui64 = uint64(math.MaxUint64)
fmt.Printf("uint64(math.MaxUint64) = %d\n", ui64)

var f32 float32
f32 = float32(ui64)
fmt.Printf("%d as 32-bit float = %0.f\n", ui64, f32)

var f64 float64
f64 = float64(ui64)
fmt.Printf("%d as 64-bit float = %0.f\n", ui64, f64)

Output:

Max unit64 value = 18446744073709551615
Max float32 value = 340282346638528859811704183484516925440.000000
Max float64 value = 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000
uint64(math.MaxUint64) = 18446744073709551615
18446744073709551615 as 32-bit float = 18446744073709551616
18446744073709551615 as 64-bit float = 18446744073709551616

Go Playground -> https://play.golang.org/p/DhlaxbFixBD

I've also tried using a big.Float, which outputs the correct Text, but gives the same results when calling the Float64() function to get a float64. That makes it seem like some type of overflow is happening, but I'm not sure if it's a constraint of the language or something I'm doing incorrectly. Assistance is greatly appreciated.

  • 1
    A 64-bit floating point only uses 52 bits (plus an implied 53rd) to represent the number itself, with another 11 used to represent the exponent, and then a sign bit. That means it cannot precisely store numbers that require more than 53 bits to represent. See [this](https://wiki.sei.cmu.edu/confluence/display/c/FLP00-C.+Understand+the+limitations+of+floating-point+numbers) and [this](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) for more details, or the link in the comment above. – Kaedys May 21 '18 at 21:25
  • Also see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – JimB May 21 '18 at 21:29

0 Answers0