github.com/vescale/zgraph@v0.0.0-20230410094002-959c02d50f95/internal/mathutil/rand_test.go (about) 1 // Copyright 2020 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package mathutil 16 17 import ( 18 "testing" 19 "time" 20 21 "github.com/stretchr/testify/require" 22 ) 23 24 func TestRandWithTime(t *testing.T) { 25 rng1 := NewWithTime() 26 // NOTE: On windows platform, this Sleep is necessary. Because time.Now() is 27 // imprecise, calling UnixNano() twice returns the same value. We have to make 28 // sure the elapsed time is longer than 1ms to get different values. 29 time.Sleep(time.Millisecond) 30 rng2 := NewWithTime() 31 got1 := rng1.Gen() 32 got2 := rng2.Gen() 33 require.True(t, got1 < 1.0) 34 require.True(t, got1 >= 0.0) 35 require.True(t, got1 != rng1.Gen()) 36 require.True(t, got2 < 1.0) 37 require.True(t, got2 >= 0.0) 38 require.True(t, got2 != rng2.Gen()) 39 require.True(t, got1 != got2) 40 } 41 42 func TestRandWithSeed(t *testing.T) { 43 tests := [4]struct { 44 seed int64 45 once float64 46 twice float64 47 }{{0, 0.15522042769493574, 0.620881741513388}, 48 {1, 0.40540353712197724, 0.8716141803857071}, 49 {-1, 0.9050373219931845, 0.37014932126752037}, 50 {9223372036854775807, 0.9050373219931845, 0.37014932126752037}} 51 for _, test := range tests { 52 rng := NewWithSeed(test.seed) 53 got1 := rng.Gen() 54 require.Equal(t, got1, test.once) 55 got2 := rng.Gen() 56 require.Equal(t, got2, test.twice) 57 } 58 } 59 60 func TestRandWithSeed1AndSeed2(t *testing.T) { 61 seed1 := uint32(10000000) 62 seed2 := uint32(1000000) 63 64 rng := NewWithTime() 65 rng.SetSeed1(seed1) 66 rng.SetSeed2(seed2) 67 68 require.Equal(t, rng.Gen(), 0.028870999839968048) 69 require.Equal(t, rng.Gen(), 0.11641535266900002) 70 require.Equal(t, rng.Gen(), 0.49546379455874096) 71 require.Equal(t, rng.GetSeed1(), uint32(532000198)) 72 require.Equal(t, rng.GetSeed2(), uint32(689000330)) 73 }