Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My result is not truly random; How can I fix this?

Tags:

c++

float genData(int low, int high);
    
int main(){
    srand(time(0)); 
    float num = genData(40, 100);
    cout << fixed << left << setprecision(2) << num << endl;
            return 0;
}
        
float genData(int low, int high) {
    low *= 100;
    high *= 100 + 1;
    int rnd = rand() % (high - low) + low;
    float newRand;
    newRand = (float) rnd / 100;
    return newRand;
}

I'm expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00

What I get is the same number with different decimal values, slowly increasing every time I run the program.


2 Answers

Use the <random> header for that:

#include <iostream>
#include <random>

float getData(int const low, int const high) {
  thread_local auto engine = std::mt19937{ std::random_device{}() };

  auto dist = std::uniform_int_distribution<int>{ low * 100, high * 100 };

  return dist(engine) / 100.0f;
}

int main() {
  for (auto i = 0; i != 5; ++i) {
    std::cout << getData(40, 100) << '\n';
  }
}
like image 166
Ayxan Haqverdili Avatar answered Jan 25 '26 21:01

Ayxan Haqverdili


Wrong range

int rnd = rand() % (high - low) + low; does not generate the right range.

float genData(int low, int high) {
  low *= 100;
  // high *= 100 + 1;
  high = high*100 + 1;

expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00

That is [40.00 ... 100.00] or 10000-4000+1 different values

int rnd = rand() % (100*(high - low) + 1) + low*100;
float frnd = rnd/100.0f; 

rand() weak here when RAND_MAX is small

With RAND_MAX == 32767, int rnd = rand() % (high - low) + low; is like [0... 32767] % 6001 + 40000. [0... 32767] % 6001 does not provide a very uniform distribution. Some values coming up 6 times and others 7-ish.

like image 29
chux - Reinstate Monica Avatar answered Jan 25 '26 20:01

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!