Search code examples
gofloating-pointlimit

Minimum positive float64 value


Just like This question, I need to a positive number that is as close to zero as possible, without it being zero, but in Go.


Solution

  • The math package has a constant for this and similar values, just use that: math.SmallestNonzeroFloat64:

    const (
        MaxFloat32             = 3.40282346638528859811704183484516925440e+38  // 2**127 * (2**24 - 1) / 2**23
        SmallestNonzeroFloat32 = 1.401298464324817070923729583289916131280e-45 // 1 / 2**(127 - 1 + 23)
    
        MaxFloat64             = 1.797693134862315708145274237317043567981e+308 // 2**1023 * (2**53 - 1) / 2**52
        SmallestNonzeroFloat64 = 4.940656458412465441765687928682213723651e-324 // 1 / 2**(1023 - 1 + 52)
    )
    

    Printing its value:

    fmt.Println(math.SmallestNonzeroFloat64)
    

    Outputs (try it on the Go Playground):

    5e-324
    

    (Note: it's greater than the constant due to rounding in the fmt package.)