golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.12k stars 17.45k forks source link

spec: clarify imprecise conversions of non-floating-point constant to floating point type #13782

Open momchil-velikov opened 8 years ago

momchil-velikov commented 8 years ago

... or perhaps the spec is does not convey the intention.

The spec says (https://golang.org/ref/spec#Conversions)

A constant value x can be converted to type T in any of these cases:

  • x is representable by a value of type T.

The Go compiler allows conversion in certain cases, where an integer constant value is not representable as a value of type float32 as in:

package main

import "fmt"

func main() {
    // bad
    const A = 0x01ffffff
    const B = float32(A)
    fmt.Printf("%d\n%f\n", A, B)

    // ok
    const C = 0x01fffffe
    const D = float32(C)
    fmt.Printf("%d\n%f\n", C, D)

    // ok
    const E = 0x00ffffff
    const F = float32(E)
    fmt.Printf("%d\n%f\n", E, F)
}

I suppose there are similar cases when converting an integer constant into float64, complex64, or complex128 type.

ianlancetaylor commented 8 years ago

Personally I think the spec should be modified so that the next line permits integer constants as well as floating-point constants to be rounded.

griesemer commented 8 years ago

Agreeing with @ianlancetaylor. This is a grey area that should be spec-ed out more precisely. (Some) rounding is acceptable when converting to floats.