本文整理汇总了Golang中math/rand.NewSource函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSource函数的具体用法?Golang NewSource怎么用?Golang NewSource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSource函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
p := fmt.Print
p(rand.Intn(100), ",")
p(rand.Intn(100))
p("\n")
p(rand.Float64(), "\n")
p((rand.Float64()*5)+5, ",")
p((rand.Float64() * 5) + 5)
p("\n")
s1 := rand.NewSource(42)
r1 := rand.New(s1)
p(r1.Intn(100), ",")
p(r1.Intn(100))
p("\n")
s2 := rand.NewSource(42)
r2 := rand.New(s2)
p(r2.Intn(100), ",")
p(r2.Intn(100))
p("\n")
}
示例2: main
func main() {
//例如,rand.Intn 返回一个随机的整数 n,0 <= n <= 100。
fmt.Print(rand.Intn(100), ",")
fmt.Print(rand.Intn(100))
fmt.Println()
//rand.Float64 返回一个64位浮点数 f,0.0 <= f <= 1.0。
fmt.Println(rand.Float64())
//这个技巧可以用来生成其他范围的随机浮点数,例如5.0 <= f <= 10.0
fmt.Print((rand.Float64()*5)+5, ",")
fmt.Print((rand.Float64() * 5) + 5)
fmt.Println()
//要让伪随机数生成器有确定性,可以给它一个明确的种子。
s1 := rand.NewSource(42)
r1 := rand.New(s1)
//调用上面返回的 rand.Source 的函数和调用 rand 包中函数是相同的。
fmt.Print(r1.Intn(100), ",")
fmt.Print(r1.Intn(100))
fmt.Println()
//如果使用相同的种子生成的随机数生成器,将会产生相同的随机数序列。
s2 := rand.NewSource(42)
r2 := rand.New(s2)
fmt.Print(r2.Intn(100), ",")
fmt.Print(r2.Intn(100))
fmt.Println()
}
示例3: main
func main() {
fmt.Print(rand.Intn(100), ",")
fmt.Print(rand.Intn(100))
fmt.Println()
fmt.Println(rand.Float64())
fmt.Print((rand.Float64()*5)+5, ",")
fmt.Print((rand.Float64() * 5) + 5)
fmt.Println()
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
fmt.Print(r1.Intn(100), ",")
fmt.Print(r1.Intn(100))
fmt.Println()
s2 := rand.NewSource(42)
r2 := rand.New(s2)
fmt.Print(r2.Intn(100), ",")
fmt.Print(r2.Intn(100))
fmt.Println()
s3 := rand.NewSource(42)
r3 := rand.New(s3)
fmt.Print(r3.Intn(100), ",")
fmt.Print(r3.Intn(100))
}
示例4: testTypeFuzzN
// Fuzz test for N iterations
func testTypeFuzzN(t *testing.T, base interface{}, ff interface{}, n int) {
require.Implements(t, (*json.Marshaler)(nil), ff)
require.Implements(t, (*json.Unmarshaler)(nil), ff)
require.Implements(t, (*marshalerFaster)(nil), ff)
require.Implements(t, (*unmarshalFaster)(nil), ff)
if _, ok := base.(unmarshalFaster); ok {
require.FailNow(t, "base should not have a UnmarshalJSONFFLexer")
}
if _, ok := base.(marshalerFaster); ok {
require.FailNow(t, "base should not have a MarshalJSONBuf")
}
f := fuzz.New()
f.NumElements(0, 1+n/40)
f.NilChance(0.2)
f.Funcs(fuzzTime, fuzzTimeSlice)
for i := 0; i < n; i++ {
f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
f.Fuzz(base)
f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
f.Fuzz(ff)
testSameMarshal(t, base, ff)
testCycle(t, base, ff)
}
}
示例5: TestBinaryDecoderBlockTable
// TestbinaryDecoderBlockTable tests many combinations of fountain block ID
// combinations to ensure that the codec has the expected reconstruction
// properties.
func TestBinaryDecoderBlockTable(t *testing.T) {
c := NewBinaryCodec(13)
message := []byte("abcdefghijklmnopqrstuvwxyz")
random := rand.New(rand.NewSource(8234923))
moreBlocksNeeded := 0
for i := 0; i < 100; i++ {
r := rand.New(rand.NewSource(random.Int63()))
ids := make([]int64, 45)
for i := range ids {
ids[i] = int64(r.Intn(100000))
}
blocks := EncodeLTBlocks(message, ids, c)
d := newBinaryDecoder(c.(*binaryCodec), len(message))
d.AddBlocks(blocks[0:30])
if !d.matrix.determined() {
moreBlocksNeeded++
d.AddBlocks(blocks[31:46])
}
decoded := d.Decode()
if !reflect.DeepEqual(decoded, message) {
t.Errorf("Decoded message doesn't match original. Got %v, want %v", decoded, message)
}
}
if moreBlocksNeeded > 2 {
t.Errorf("Needed too many high-block-count decoding sequences: %d", moreBlocksNeeded)
}
}
示例6: TestBinaryDecodeMessageTable
// TestBinaryDecodeMessageTable tests a large number of source messages to make
// sure they are all reconstructed accurately. This provides assurance that the
// decoder is functioning accurately.
func TestBinaryDecodeMessageTable(t *testing.T) {
c := NewBinaryCodec(10)
random := rand.New(rand.NewSource(8234982))
for i := 0; i < 100; i++ {
r := rand.New(rand.NewSource(random.Int63()))
messageLen := r.Intn(1000) + 1000
message := make([]byte, messageLen)
for j := 0; j < len(message); j++ {
message[j] = byte(r.Intn(200))
}
ids := make([]int64, 50)
for i := range ids {
ids[i] = int64(r.Intn(100000))
}
blocks := EncodeLTBlocks(message, ids, c)
d := newBinaryDecoder(c.(*binaryCodec), len(message))
d.AddBlocks(blocks[0:25])
if !d.matrix.determined() {
t.Errorf("Message should be determined after 25 blocks")
} else {
decoded := d.Decode()
if !reflect.DeepEqual(decoded, message) {
t.Errorf("Incorrect message decode. Length=%d, message=%v", len(message), message)
}
}
}
}
示例7: TestDecodeMessageTable
func TestDecodeMessageTable(t *testing.T) {
c := NewOnlineCodec(10, 0.2, 7, 0).(*onlineCodec)
random := rand.New(rand.NewSource(8234982))
for i := 0; i < 100; i++ {
c.randomSeed = random.Int63()
r := rand.New(rand.NewSource(random.Int63()))
messageLen := r.Intn(1000) + 1000
message := make([]byte, messageLen)
for j := 0; j < len(message); j++ {
message[j] = byte(r.Intn(200))
}
ids := make([]int64, 50)
for i := range ids {
ids[i] = int64(r.Intn(100000))
}
blocks := encodeOnlineBlocks(message, ids, *c)
d := newOnlineDecoder(c, len(message))
d.AddBlocks(blocks[0:25])
if !d.matrix.determined() {
t.Errorf("Message should be determined after 25 blocks")
} else {
decoded := d.Decode()
if !reflect.DeepEqual(decoded, message) {
t.Errorf("Incorrect message decode. Length=%d", len(message))
}
}
}
}
示例8: innerBroadcast
// Marshals a Message and hands it to the Stack. If toSelf is true,
// the message is also dispatched to the local instance's RecvMsgSync.
func (instance *pbftCore) innerBroadcast(msg *Message) error {
msgRaw, err := proto.Marshal(msg)
if err != nil {
return fmt.Errorf("Cannot marshal message %s", err)
}
doByzantine := false
if instance.byzantine {
rand1 := rand.New(rand.NewSource(time.Now().UnixNano()))
doIt := rand1.Intn(3) // go byzantine about 1/3 of the time
if doIt == 1 {
doByzantine = true
}
}
// testing byzantine fault.
if doByzantine {
rand2 := rand.New(rand.NewSource(time.Now().UnixNano()))
ignoreidx := rand2.Intn(instance.N)
for i := 0; i < instance.N; i++ {
if i != ignoreidx && uint64(i) != instance.id { //Pick a random replica and do not send message
instance.consumer.unicast(msgRaw, uint64(i))
} else {
logger.Debugf("PBFT byzantine: not broadcasting to replica %v", i)
}
}
} else {
instance.consumer.broadcast(msgRaw)
}
return nil
}
示例9: outOfOrder
func outOfOrder(l *list.List) {
iTotal := 25
if iTotal > l.Len() {
iTotal = l.Len()
}
ll := make([]*list.List, iTotal)
for i := 0; i < iTotal; i++ {
ll[i] = list.New()
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for e := l.Front(); e != nil; e = e.Next() {
fpath, ok := e.Value.(string)
if !ok {
panic("The path is invalid string")
}
if rand.Int()%2 == 0 {
ll[r.Intn(iTotal)].PushFront(fpath)
} else {
ll[r.Intn(iTotal)].PushBack(fpath)
}
}
r0 := rand.New(rand.NewSource(time.Now().UnixNano()))
l.Init()
for i := 0; i < iTotal; i++ {
if r0.Intn(2) == 0 {
l.PushBackList(ll[i])
} else {
l.PushFrontList(ll[i])
}
ll[i].Init()
}
}
示例10: main
func main() {
fmt.Print(rand.Intn(100), ",") // rand.Intn returns random in between 0,99
fmt.Print(rand.Intn(100))
fmt.Println()
fmt.Println(rand.Float64) // random float f where 0.0 <= f < 1.0
fmt.Print((rand.Float64()*5)+5, ",")
fmt.Print((rand.Float64() * 5) + 5) // float f where 5.0 <= 5 < 10.0
fmt.Println()
// default random number generator will produce same sequence of numbers by default
// give it a seed that changes for varying sequences
// if you seed a source with the same number, it produces the same sequence of random numbers
// USE crypto/rand FOR SECRET RANDOM NUMBERS
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
fmt.Print(r1.Intn(100), ",")
fmt.Print(r1.Intn(100))
fmt.Println()
s2 := rand.NewSource(42)
r2 := rand.New(s2)
fmt.Print(r2.Intn(100), ",")
fmt.Print(r2.Intn(100))
fmt.Println()
s3 := rand.NewSource(42)
r3 := rand.New(s3)
fmt.Print(r3.Intn(100), ",")
fmt.Print(r2.Intn(100))
}
示例11: main
func main() {
// For example, `rand.Intn` returns a random `int` n,
// `0 <= n < 100`.
fmt.Print(rand.Intn(100), ",")
fmt.Print(rand.Intn(100))
fmt.Println()
// `rand.Float64` returns a `float64` `f`,
// `0.0 <= f < 1.0`.
fmt.Println(rand.Float64())
// To make the psuedo-random generator deterministic,
// give it a well-known seed.
s1 := rand.NewSource(42)
r1 := rand.New(s1)
// Call the resulting `rand.Source` just like the
// functions on the `rand` package.
fmt.Print(r1.Intn(100), ",")
fmt.Print(r1.Intn(100))
fmt.Println()
// If you seed a source with the same number, it
// produces the same sequence of random numbers.
s2 := rand.NewSource(42)
r2 := rand.New(s2)
fmt.Print(r2.Intn(100), ",")
fmt.Print(r2.Intn(100))
fmt.Println()
}
示例12: Test
func Test(t *testing.T) {
t.Parallel()
Convey("test mathrand", t, func() {
now := time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)
c, _ := testclock.UseTime(context.Background(), now)
// Note that the non-randomness below is because time is fixed at the
// top of the outer test function. Normally it would evolve with time.
Convey("unset", func() {
r := rand.New(rand.NewSource(now.UnixNano()))
i := r.Int()
So(Get(c).Int(), ShouldEqual, i)
So(Get(c).Int(), ShouldEqual, i)
})
Convey("set persistance", func() {
c = Set(c, rand.New(rand.NewSource(now.UnixNano())))
r := rand.New(rand.NewSource(now.UnixNano()))
So(Get(c).Int(), ShouldEqual, r.Int())
So(Get(c).Int(), ShouldEqual, r.Int())
})
Convey("nil set", func() {
c = Set(c, nil)
r := rand.New(rand.NewSource(now.UnixNano()))
i := r.Int()
So(Get(c).Int(), ShouldEqual, i)
So(Get(c).Int(), ShouldEqual, i)
})
})
}
示例13: MakeAllocator
// MakeAllocator creates a new allocator using the specified StorePool.
func MakeAllocator(storePool *StorePool, options AllocatorOptions) Allocator {
var randSource rand.Source
if options.Deterministic {
randSource = rand.NewSource(777)
} else {
randSource = rand.NewSource(rand.Int63())
}
a := Allocator{
storePool: storePool,
options: options,
randGen: makeAllocatorRand(randSource),
}
// Instantiate balancer based on provided options.
switch options.Mode {
case BalanceModeUsage:
a.balancer = usageBalancer{a.randGen}
case BalanceModeRangeCount:
a.balancer = rangeCountBalancer{a.randGen}
default:
panic(fmt.Sprintf("AllocatorOptions specified invalid BalanceMode %d", options.Mode))
}
return a
}
示例14: New
func New(db database.Database, dbConfig config.DbConfig) strategy.Strategy {
return &rankStrategy{
isNewRand: rand.New(rand.NewSource(time.Now().Unix())),
rankRand: rand.New(rand.NewSource(time.Now().Add(time.Hour).Unix())),
db: db,
dbConfig: dbConfig,
}
}
示例15: TestTargetRequest
func TestTargetRequest(t *testing.T) {
t.Parallel()
body := []byte(`{"id": "{foo}", "value": "bar"}`)
tgt := Target{
Method: "GET",
URL: "http://{foo}:9999/",
Body: body,
Header: http.Header{
"X-Some-Header": []string{"1"},
"X-Some-Other-Header": []string{"2"},
"X-Some-New-Header": []string{"3"},
"Host": []string{"lolcathost"},
},
URLInterpolators: []URLInterpolator{
&RandomNumericInterpolation{
Key: "{foo}",
Limit: int(^uint(0) >> 1),
Rand: rand.New(rand.NewSource(1435875839)),
},
},
BodyInterpolators: []BodyInterpolator{
&RandomNumericInterpolation{
Key: "{foo}",
Limit: int(^uint(0) >> 1),
Rand: rand.New(rand.NewSource(1435875839)),
},
},
}
req, _ := tgt.Request()
reqBody, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal([]byte(`{"id": "2290778204292519845", "value": "bar"}`), reqBody) {
t.Fatalf("Target body wasn't copied correctly")
}
if req.URL.String() != "http://2290778204292519845:9999/" {
t.Fatalf("Target URL wasn't resolved correctly")
}
tgt.Header.Set("X-Stuff", "0")
if req.Header.Get("X-Stuff") == "0" {
t.Error("Each Target must have its own Header")
}
want, got := tgt.Header.Get("Host"), req.Header.Get("Host")
if want != got {
t.Fatalf("Target Header wasn't copied correctly. Want: %s, Got: %s", want, got)
}
if req.Host != want {
t.Fatalf("Target Host wasnt copied correctly. Want: %s, Got: %s", want, req.Host)
}
}