will this generate a random number correctly

I'm trying to generate a random number between x and y. Will this do what I want without significant biasing?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cstdlib>
#include <ctime>

int main ()
{
    srand (time (NULL));
    double x, y;
    std::cin >> x >> y;
    double range = y - x;
    double randFloat = rand () / RAND_MAX;
    double randNum = (randFloat * range) + x;
    std::cout << randNum << std::endl;

    // just so you can see the result
    int asdf;
    std::cin >> asdf;
    
    return 0;
}
Yes, but the bias is in the RNG, not the algorithm you posted.
For unbiased random numbers, you need to use a better RNG. Google around for one. Good luck!
After testing this, it turns out that "random" number is always the x value entered because randFloat somehow is always 0. Where did I go wrong?
rand() gives an int. RAND_MAX is an int. Therefore rand() / RAND_MAX will do integer division and the result is 0 (except if rand() returns RAND_MAX). What you have to do is to cast at least one side of the division to a floating point number.
double randFloat = static_cast<double>(rand()) / RAND_MAX;
Last edited on
It works perfectly now, thank you!
Yoinks! Sorry I missed that!
Topic archived. No new replies allowed.