tags:

views:

351

answers:

2

how to generate random numbers between two doubles in c++ , these number should look like xxxxx,yyyyy .

thanks

+4  A: 

Here's how

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

Remember to call srand() with a proper seed each time your program starts.

rep_movsd
to exclude max (often done): add +1 to RAND_MAX
KillianDS
If you add 1 to RAND_MAX, do so carefully, since it might be equal to INT_MAX. `double f = rand() / (RAND_MAX + 1.0);`
Steve Jessop
Note that the randomness of this can be limited. The range xxxxx,yyyyy suggests 10 decimal digits. There are plenty of systems where RAND_MAX is smaller than 10^10. This would mean that some numbers in that range have `p(xxxxx,yyyyy)==0.0`
MSalters
A: 

something like this:

#include <iostream>
#include <time.h>

using namespace std;

int main()
{
    const long max_rand = 1000000L;
    double x1 = 12.33, x2 = 34.123, x;

    srandom(time(NULL));

    x = x1 + ( x2 - x1) * (random() % max_rand) / max_rand;

    cout << x1 << " <= " << x << " <= " << x2 << endl;

    return 0;
}
oraz