When I cast math.NaN() and math.MaxFloat64 to int, Why the result is different between go1.14.2 and go1.17.2?

Issue

package main

import (
    "fmt"
    "math"
)

func main() {
    x, y := math.NaN(), math.MaxFloat64
    fmt.Printf("%d\n", int(x))
    fmt.Printf("%d\n", int(y))
}

That is my test code snippet. When I run the above code use go1.14.2, the result is

-9223372036854775808
-9223372036854775808

but the same code run in go1.17.2, the result is

0
9223372036854775807

I searched the simular question: Why Is uint64 of NaN and MaxFloat64 equal in Golang?, which said that in the different hardware environment, the math.NaN() maybe different, but I run the code both in my MacOS M1 system, just golang version is different. Why the result is different between go1.14.2 and go1.17.2?

Solution

Spec: Conversions:

In all non-constant conversions involving floating-point or complex values, if the result type cannot represent the value the conversion succeeds but the result value is implementation-dependent.

You convert the floating-point value NaN to int. The valid values of the int type does not include the NaN value, so the value you convert cannot be represented by a value of type int, so the result is implementation-dependent. Basically, the spec allows it to be changed from version to version, from platform to platform. You cannot (should not) assume a specific int value for the conversion result.

Answered By – icza

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.