3.8 随机数

Posted cucy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.8 随机数相关的知识,希望对你有一定的参考价值。


package main

import (
    crypto "crypto/rand"
    "fmt"
    "math/big"
    "math/rand"
)

func main() {

    sec1 := rand.New(rand.NewSource(10))
    sec2 := rand.New(rand.NewSource(10))
    for i := 0; i < 5; i++ {
        rnd1 := sec1.Int()
        rnd2 := sec2.Int()
        if rnd1 != rnd2 {
            fmt.Println("Rand generated non-equal sequence")
            break
        } else {
            fmt.Printf("Math/Rand1: %d , Math/Rand2: %d\n", rnd1, rnd2)
        }
    }

    for i := 0; i < 5; i++ {
        safeNum := NewCryptoRand()
        safeNum2 := NewCryptoRand()
        if safeNum == safeNum2 {
            fmt.Println("Crypto generated equal numbers")
            break
        } else {
            fmt.Printf("Crypto/Rand1: %d , Crypto/Rand2: %d\n", safeNum, safeNum2)
        }
    }
}

func NewCryptoRand() int64 {
    safeNum, err := crypto.Int(crypto.Reader, big.NewInt(100234))
    if err != nil {
        panic(err)
    }
    return safeNum.Int64()
}

/*
Math/Rand1: 5221277731205826435 , Math/Rand2: 5221277731205826435
Math/Rand1: 3852159813000522384 , Math/Rand2: 3852159813000522384
Math/Rand1: 8532807521486154107 , Math/Rand2: 8532807521486154107
Math/Rand1: 3888302351045490779 , Math/Rand2: 3888302351045490779
Math/Rand1: 4512466281294657143 , Math/Rand2: 4512466281294657143
Crypto/Rand1: 8037 , Crypto/Rand2: 39548
Crypto/Rand1: 70036 , Crypto/Rand2: 36267
Crypto/Rand1: 57332 , Crypto/Rand2: 51974
Crypto/Rand1: 71516 , Crypto/Rand2: 5445
Crypto/Rand1: 62317 , Crypto/Rand2: 61380

*/

以上是关于3.8 随机数的主要内容,如果未能解决你的问题,请参考以下文章

播放随机声音而不重复

21个常用代码片段

PHP 代码片段

java获取随机时间的源码片段

正在渲染opengl的随机屏幕片段-这表明啥错误?

HTML代码片段