OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [math/] [rand/] [rand_test.go] - Blame information for rev 747

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// Copyright 2009 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
4
 
5
package rand
6
 
7
import (
8
        "errors"
9
        "fmt"
10
        "math"
11
        "testing"
12
)
13
 
14
const (
15
        numTestSamples = 10000
16
)
17
 
18
type statsResults struct {
19
        mean        float64
20
        stddev      float64
21
        closeEnough float64
22
        maxError    float64
23
}
24
 
25
func max(a, b float64) float64 {
26
        if a > b {
27
                return a
28
        }
29
        return b
30
}
31
 
32
func nearEqual(a, b, closeEnough, maxError float64) bool {
33
        absDiff := math.Abs(a - b)
34
        if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
35
                return true
36
        }
37
        return absDiff/max(math.Abs(a), math.Abs(b)) < maxError
38
}
39
 
40
var testSeeds = []int64{1, 1754801282, 1698661970, 1550503961}
41
 
42
// checkSimilarDistribution returns success if the mean and stddev of the
43
// two statsResults are similar.
44
func (this *statsResults) checkSimilarDistribution(expected *statsResults) error {
45
        if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) {
46
                s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
47
                fmt.Println(s)
48
                return errors.New(s)
49
        }
50
        if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) {
51
                s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
52
                fmt.Println(s)
53
                return errors.New(s)
54
        }
55
        return nil
56
}
57
 
58
func getStatsResults(samples []float64) *statsResults {
59
        res := new(statsResults)
60
        var sum float64
61
        for i := range samples {
62
                sum += samples[i]
63
        }
64
        res.mean = sum / float64(len(samples))
65
        var devsum float64
66
        for i := range samples {
67
                devsum += math.Pow(samples[i]-res.mean, 2)
68
        }
69
        res.stddev = math.Sqrt(devsum / float64(len(samples)))
70
        return res
71
}
72
 
73
func checkSampleDistribution(t *testing.T, samples []float64, expected *statsResults) {
74
        actual := getStatsResults(samples)
75
        err := actual.checkSimilarDistribution(expected)
76
        if err != nil {
77
                t.Errorf(err.Error())
78
        }
79
}
80
 
81
func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) {
82
        chunk := len(samples) / nslices
83
        for i := 0; i < nslices; i++ {
84
                low := i * chunk
85
                var high int
86
                if i == nslices-1 {
87
                        high = len(samples) - 1
88
                } else {
89
                        high = (i + 1) * chunk
90
                }
91
                checkSampleDistribution(t, samples[low:high], expected)
92
        }
93
}
94
 
95
//
96
// Normal distribution tests
97
//
98
 
99
func generateNormalSamples(nsamples int, mean, stddev float64, seed int64) []float64 {
100
        r := New(NewSource(seed))
101
        samples := make([]float64, nsamples)
102
        for i := range samples {
103
                samples[i] = r.NormFloat64()*stddev + mean
104
        }
105
        return samples
106
}
107
 
108
func testNormalDistribution(t *testing.T, nsamples int, mean, stddev float64, seed int64) {
109
        //fmt.Printf("testing nsamples=%v mean=%v stddev=%v seed=%v\n", nsamples, mean, stddev, seed);
110
 
111
        samples := generateNormalSamples(nsamples, mean, stddev, seed)
112
        errorScale := max(1.0, stddev) // Error scales with stddev
113
        expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}
114
 
115
        // Make sure that the entire set matches the expected distribution.
116
        checkSampleDistribution(t, samples, expected)
117
 
118
        // Make sure that each half of the set matches the expected distribution.
119
        checkSampleSliceDistributions(t, samples, 2, expected)
120
 
121
        // Make sure that each 7th of the set matches the expected distribution.
122
        checkSampleSliceDistributions(t, samples, 7, expected)
123
}
124
 
125
// Actual tests
126
 
127
func TestStandardNormalValues(t *testing.T) {
128
        for _, seed := range testSeeds {
129
                testNormalDistribution(t, numTestSamples, 0, 1, seed)
130
        }
131
}
132
 
133
func TestNonStandardNormalValues(t *testing.T) {
134
        sdmax := 1000.0
135
        mmax := 1000.0
136
        if testing.Short() {
137
                sdmax = 5
138
                mmax = 5
139
        }
140
        for sd := 0.5; sd < sdmax; sd *= 2 {
141
                for m := 0.5; m < mmax; m *= 2 {
142
                        for _, seed := range testSeeds {
143
                                testNormalDistribution(t, numTestSamples, m, sd, seed)
144
                        }
145
                }
146
        }
147
}
148
 
149
//
150
// Exponential distribution tests
151
//
152
 
153
func generateExponentialSamples(nsamples int, rate float64, seed int64) []float64 {
154
        r := New(NewSource(seed))
155
        samples := make([]float64, nsamples)
156
        for i := range samples {
157
                samples[i] = r.ExpFloat64() / rate
158
        }
159
        return samples
160
}
161
 
162
func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed int64) {
163
        //fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed);
164
 
165
        mean := 1 / rate
166
        stddev := mean
167
 
168
        samples := generateExponentialSamples(nsamples, rate, seed)
169
        errorScale := max(1.0, 1/rate) // Error scales with the inverse of the rate
170
        expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.20 * errorScale}
171
 
172
        // Make sure that the entire set matches the expected distribution.
173
        checkSampleDistribution(t, samples, expected)
174
 
175
        // Make sure that each half of the set matches the expected distribution.
176
        checkSampleSliceDistributions(t, samples, 2, expected)
177
 
178
        // Make sure that each 7th of the set matches the expected distribution.
179
        checkSampleSliceDistributions(t, samples, 7, expected)
180
}
181
 
182
// Actual tests
183
 
184
func TestStandardExponentialValues(t *testing.T) {
185
        for _, seed := range testSeeds {
186
                testExponentialDistribution(t, numTestSamples, 1, seed)
187
        }
188
}
189
 
190
func TestNonStandardExponentialValues(t *testing.T) {
191
        for rate := 0.05; rate < 10; rate *= 2 {
192
                for _, seed := range testSeeds {
193
                        testExponentialDistribution(t, numTestSamples, rate, seed)
194
                }
195
        }
196
}
197
 
198
//
199
// Table generation tests
200
//
201
 
202
func initNorm() (testKn []uint32, testWn, testFn []float32) {
203
        const m1 = 1 << 31
204
        var (
205
                dn float64 = rn
206
                tn         = dn
207
                vn float64 = 9.91256303526217e-3
208
        )
209
 
210
        testKn = make([]uint32, 128)
211
        testWn = make([]float32, 128)
212
        testFn = make([]float32, 128)
213
 
214
        q := vn / math.Exp(-0.5*dn*dn)
215
        testKn[0] = uint32((dn / q) * m1)
216
        testKn[1] = 0
217
        testWn[0] = float32(q / m1)
218
        testWn[127] = float32(dn / m1)
219
        testFn[0] = 1.0
220
        testFn[127] = float32(math.Exp(-0.5 * dn * dn))
221
        for i := 126; i >= 1; i-- {
222
                dn = math.Sqrt(-2.0 * math.Log(vn/dn+math.Exp(-0.5*dn*dn)))
223
                testKn[i+1] = uint32((dn / tn) * m1)
224
                tn = dn
225
                testFn[i] = float32(math.Exp(-0.5 * dn * dn))
226
                testWn[i] = float32(dn / m1)
227
        }
228
        return
229
}
230
 
231
func initExp() (testKe []uint32, testWe, testFe []float32) {
232
        const m2 = 1 << 32
233
        var (
234
                de float64 = re
235
                te         = de
236
                ve float64 = 3.9496598225815571993e-3
237
        )
238
 
239
        testKe = make([]uint32, 256)
240
        testWe = make([]float32, 256)
241
        testFe = make([]float32, 256)
242
 
243
        q := ve / math.Exp(-de)
244
        testKe[0] = uint32((de / q) * m2)
245
        testKe[1] = 0
246
        testWe[0] = float32(q / m2)
247
        testWe[255] = float32(de / m2)
248
        testFe[0] = 1.0
249
        testFe[255] = float32(math.Exp(-de))
250
        for i := 254; i >= 1; i-- {
251
                de = -math.Log(ve/de + math.Exp(-de))
252
                testKe[i+1] = uint32((de / te) * m2)
253
                te = de
254
                testFe[i] = float32(math.Exp(-de))
255
                testWe[i] = float32(de / m2)
256
        }
257
        return
258
}
259
 
260
// compareUint32Slices returns the first index where the two slices
261
// disagree, or <0 if the lengths are the same and all elements
262
// are identical.
263
func compareUint32Slices(s1, s2 []uint32) int {
264
        if len(s1) != len(s2) {
265
                if len(s1) > len(s2) {
266
                        return len(s2) + 1
267
                }
268
                return len(s1) + 1
269
        }
270
        for i := range s1 {
271
                if s1[i] != s2[i] {
272
                        return i
273
                }
274
        }
275
        return -1
276
}
277
 
278
// compareFloat32Slices returns the first index where the two slices
279
// disagree, or <0 if the lengths are the same and all elements
280
// are identical.
281
func compareFloat32Slices(s1, s2 []float32) int {
282
        if len(s1) != len(s2) {
283
                if len(s1) > len(s2) {
284
                        return len(s2) + 1
285
                }
286
                return len(s1) + 1
287
        }
288
        for i := range s1 {
289
                if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) {
290
                        return i
291
                }
292
        }
293
        return -1
294
}
295
 
296
func TestNormTables(t *testing.T) {
297
        testKn, testWn, testFn := initNorm()
298
        if i := compareUint32Slices(kn[0:], testKn); i >= 0 {
299
                t.Errorf("kn disagrees at index %v; %v != %v", i, kn[i], testKn[i])
300
        }
301
        if i := compareFloat32Slices(wn[0:], testWn); i >= 0 {
302
                t.Errorf("wn disagrees at index %v; %v != %v", i, wn[i], testWn[i])
303
        }
304
        if i := compareFloat32Slices(fn[0:], testFn); i >= 0 {
305
                t.Errorf("fn disagrees at index %v; %v != %v", i, fn[i], testFn[i])
306
        }
307
}
308
 
309
func TestExpTables(t *testing.T) {
310
        testKe, testWe, testFe := initExp()
311
        if i := compareUint32Slices(ke[0:], testKe); i >= 0 {
312
                t.Errorf("ke disagrees at index %v; %v != %v", i, ke[i], testKe[i])
313
        }
314
        if i := compareFloat32Slices(we[0:], testWe); i >= 0 {
315
                t.Errorf("we disagrees at index %v; %v != %v", i, we[i], testWe[i])
316
        }
317
        if i := compareFloat32Slices(fe[0:], testFe); i >= 0 {
318
                t.Errorf("fe disagrees at index %v; %v != %v", i, fe[i], testFe[i])
319
        }
320
}
321
 
322
// Benchmarks
323
 
324
func BenchmarkInt63Threadsafe(b *testing.B) {
325
        for n := b.N; n > 0; n-- {
326
                Int63()
327
        }
328
}
329
 
330
func BenchmarkInt63Unthreadsafe(b *testing.B) {
331
        r := New(NewSource(1))
332
        for n := b.N; n > 0; n-- {
333
                r.Int63()
334
        }
335
}
336
 
337
func BenchmarkIntn1000(b *testing.B) {
338
        r := New(NewSource(1))
339
        for n := b.N; n > 0; n-- {
340
                r.Intn(1000)
341
        }
342
}
343
 
344
func BenchmarkInt63n1000(b *testing.B) {
345
        r := New(NewSource(1))
346
        for n := b.N; n > 0; n-- {
347
                r.Int63n(1000)
348
        }
349
}
350
 
351
func BenchmarkInt31n1000(b *testing.B) {
352
        r := New(NewSource(1))
353
        for n := b.N; n > 0; n-- {
354
                r.Int31n(1000)
355
        }
356
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.