• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2014 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // random_utils:
7 //   Helper functions for random number generation.
8 //
9 
10 #include "random_utils.h"
11 
12 #include <chrono>
13 
14 #include <cstdlib>
15 
16 namespace angle
17 {
18 
19 // Seed from clock
RNG()20 RNG::RNG()
21 {
22     long long timeSeed = std::chrono::system_clock::now().time_since_epoch().count();
23     mGenerator.seed(static_cast<unsigned int>(timeSeed));
24 }
25 
26 // Seed from fixed number.
RNG(unsigned int seed)27 RNG::RNG(unsigned int seed) : mGenerator(seed) {}
28 
~RNG()29 RNG::~RNG() {}
30 
reseed(unsigned int newSeed)31 void RNG::reseed(unsigned int newSeed)
32 {
33     mGenerator.seed(newSeed);
34 }
35 
randomBool(float probTrue)36 bool RNG::randomBool(float probTrue)
37 {
38     std::bernoulli_distribution dist(probTrue);
39     return dist(mGenerator);
40 }
41 
randomInt()42 int RNG::randomInt()
43 {
44     std::uniform_int_distribution<int> intDistribution;
45     return intDistribution(mGenerator);
46 }
47 
randomIntBetween(int min,int max)48 int RNG::randomIntBetween(int min, int max)
49 {
50     std::uniform_int_distribution<int> intDistribution(min, max);
51     return intDistribution(mGenerator);
52 }
53 
randomUInt()54 unsigned int RNG::randomUInt()
55 {
56     std::uniform_int_distribution<unsigned int> uintDistribution;
57     return uintDistribution(mGenerator);
58 }
59 
randomFloat()60 float RNG::randomFloat()
61 {
62     std::uniform_real_distribution<float> floatDistribution;
63     return floatDistribution(mGenerator);
64 }
65 
randomFloatBetween(float min,float max)66 float RNG::randomFloatBetween(float min, float max)
67 {
68     std::uniform_real_distribution<float> floatDistribution(min, max);
69     return floatDistribution(mGenerator);
70 }
71 
randomFloatNonnegative()72 float RNG::randomFloatNonnegative()
73 {
74     std::uniform_real_distribution<float> floatDistribution(0.0f,
75                                                             std::numeric_limits<float>::max());
76     return floatDistribution(mGenerator);
77 }
78 
randomNegativeOneToOne()79 float RNG::randomNegativeOneToOne()
80 {
81     return randomFloatBetween(-1.0f, 1.0f);
82 }
83 
84 }  // namespace angle
85