百万分之一的Golang 1

I'm learning some Go and I'm doing some interview exercises. I have one exercice where one is asked to perform some operation randomly with a 1 in a million probability.

Let's say that I want to return true once in a million.

If my math is still right (and Google too), I would calculate this with the expression math.Pow(1-(1/1000000),1000000) however this keeps returning me 1 constantly, which doesn't seem correct.

Given this description, how could I ensure that I'd return true only once in a million? This sounds trivial but I'm really struggling with it.

Go standard library has a rand package and it has Intn() function that will give you a pseudo-random number in the range of [0 , n). So to fire an event with probability of 1/1000000 you could do something like

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    n := rand.Intn(1000000)
    if n == 154397 {
        fmt.Println("I am a lucky bastard!")
    } else {
        fmt.Println("I am not")
    }
}

Needless to say that 154397 could be replaced with any other integer in range. Link to playground

the expression math.Pow(1-(1/1000000),1000000) however this keeps returning me 1 constantly, which doesn't seem correct.


1/1000000 is zero. Integer division truncates towards zero.

Use floating-point, 1.0 not 1:

package main

import (
    "fmt"
    "math"
)

func main() {
    p := math.Pow(1-(1/1000000), 1000000)
    fmt.Println(p)
    p = math.Pow(1-(1.0/1000000), 1000000)
    fmt.Println(p)
}

Playground: https://play.golang.org/p/ZhUAe6imaNv

Output:

1
0.36787925722078507