乱数生成整理(C++,Go)
年前に乱数に悩まされ、整理記録に時間があった.乱数生成は真と偽の2種類に分けられる.通常は開発言語が持つランダム関数で生成すればよいが、
しかし、実際の場合、サードパーティの真のランダム生成ライブラリまたはシステム特殊デバイスを呼び出して真のランダム数を生成することができます.Linuxでは「/dev/random」または「/dev/urandom」で生成できます.
この2つのファイルについては、ウィキペディアを参照してください.
https://zh.wikipedia.org/wiki//dev/random
C++とGoバージョンのランダム関連コードを整理しました.
Go版:
符号化の際,C++11は乱数生成エンジンと乱数分布により多くの選択をカプセル化し,サードパーティライブラリも比較的多く,Goでは,特に要求されるランダム効果を実現するには,より多くの処理を手作業で行う必要があることが分かった.
また、乱数生成は実際に使用されている場合、注意しないと初心者がよく犯す間違いの一つは、Goでは「time.Now().Unix()」をランダムシードとして使用し、for{}で一括する不合理である.
乱数を生成して、それから多くの繰り返しの乱数が得られたことを発見して、私はすでに同僚に穴をあけられました.の
Blog: http://blog.csdn.net/xcl168
しかし、実際の場合、サードパーティの真のランダム生成ライブラリまたはシステム特殊デバイスを呼び出して真のランダム数を生成することができます.Linuxでは「/dev/random」または「/dev/urandom」で生成できます.
この2つのファイルについては、ウィキペディアを参照してください.
https://zh.wikipedia.org/wiki//dev/random
C++とGoバージョンのランダム関連コードを整理しました.
#include
#include
#include
#include
//////////////////////////////////////////////////
// C++11
//
// : http://www.cplusplus.com/reference/random/
// https://www.zhihu.com/question/20423025
// Author: XCL
// Date: 2017-2-12
//////////////////////////////////////////////////
// int
void t1(){
// uniform_int_distribution, mersenne_twister , [99000000, 99000010]
std::mt19937_64::result_type seed = std::chrono::system_clock::now().time_since_epoch().count();
auto dice_rand = std::bind(std::uniform_int_distribution(99000000,99000010),std::mt19937_64(seed));
for(int i = 0; i < 10; i++){
std::cout << dice_rand() << " " ;
}
std::cout<<:endl true="" void="" t2="" std::default_random_engine="" generator="" std::bernoulli_distribution="" distribution="" for="" i="0;" std::cout="" int="" main="" t1="" return=""/>
Go版:
package main
/*
Go
:
https://zh.wikipedia.org/wiki//dev/random
https://gobyexample.com/random-numbers
https://golang.org/pkg/crypto/rand/
Author: XCL
Date: 2017-2-12
*/
import (
crand "crypto/rand"
"encoding/binary"
"fmt"
mrand "math/rand"
"os"
"time"
)
// int
func a1() {
s1 := mrand.NewSource(time.Now().UnixNano())
r1 := mrand.New(s1)
for i := 0; i < 10; i++ {
fmt.Printf("%d ", r1.Intn(100))
}
fmt.Printf("
")
}
// 0/1 true/false
func a2() {
// Go .
ch := make(chan int, 1)
for i := 0; i < 10; i++ {
select {
case ch
符号化の際,C++11は乱数生成エンジンと乱数分布により多くの選択をカプセル化し,サードパーティライブラリも比較的多く,Goでは,特に要求されるランダム効果を実現するには,より多くの処理を手作業で行う必要があることが分かった.
また、乱数生成は実際に使用されている場合、注意しないと初心者がよく犯す間違いの一つは、Goでは「time.Now().Unix()」をランダムシードとして使用し、for{}で一括する不合理である.
乱数を生成して、それから多くの繰り返しの乱数が得られたことを発見して、私はすでに同僚に穴をあけられました.の
Blog: http://blog.csdn.net/xcl168