user17038887
user17038887

Reputation:

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

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.

Upvotes: 2

Views: 157

Answers (3)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

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';
  }
}

Upvotes: 4

chux
chux

Reputation: 153498

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.

Upvotes: 3

Mostafa Wael
Mostafa Wael

Reputation: 3838

If you are using C++ 11 you can use better random number generators that will give you diversity in the generated numbers in addition to being a lot faster.

Quick Example:

#include <random> // The header for the generators.
#include <ctime> // To seed the generator.
 
// Generating random numbers with C++11's random requires an engine and a distribution.
mt19937_64 rng(seed);
// For instance, we will create a uniform distribution for integers in the (low, high) range:
uniform_int_distribution<int> unii(low, high);
// Show the random number
cout << unii(rng) << ' ';

You can follow this article for more explanation from here.

Upvotes: 1

Related Questions