Saturday 4 September 2021

Go Random Number Generation

 We can generate random number using rand object. We should provide some seeding to rand object so that the number generated are different. If we does not provide the seeding then the compiler always produce the same result.

Go Random Number Generation

  1. package main  
  2.   
  3. import "fmt"  
  4. import (  
  5.     "math/rand"  
  6.     //"time"  
  7.     "time"  
  8. )  
  9. func main() {  
  10.     fmt.Print(rand.Intn(100))  //will produce random integer between 0 to 100  
  11.     fmt.Println()  
  12.   
  13.     fmt.Print(rand.Float64())   // will produce random number between 0 to 1  
  14.     fmt.Println()  
  15.       
  16.     rand.Seed(time.Now().Unix())  // seeding do that random number will produced  
  17.     myrand := random(120)  
  18.   
  19.     fmt.Println(myrand)  
  20.   
  21. }  
  22.   
  23. func random(min, max intint {  
  24.     return rand.Intn(max - min) + min  
  25. }  

Output:

81
0.9405090880450124
17

No comments:

Post a Comment