Saturday, June 5, 2010

Random numbers in c++

As you know, in c++ there is one function for create random numbers. And it is:

rand();

But in rand() function, we can't giving minimum or maximum number. This function return 0 between RAND_MAX value.

And when you call rand() function, you will get same thing every time.

Example, if we try this code;

#include <stdlib.h>
#include <iostream>

using namespace std;

int main ()
{
    cout<<rand()<<endl;
    cout<<rand();
    return 0;
}
Return will be same number. But if we use srand() function, when we call rand() it's will return different number;

int main ()
{
    srand(time(0));
    cout<<rand()<<endl;
    cout<<rand();
    return 0;
}

Now, we want giving max and min numbers.

double rmax,rmin,d,final;
rmin=20;
rmax=100;
int r=rand();
d=rmax-rmin;
final=rmin+(d*(float)r/RAND_MAX);

Let's look to code; in example, out RAND_MAX value is 1000
First we create our values. In this example rmax=100, rmin=20.
And we giving rand() to int r. Let's sat it's 250.

Now our diffence (d) is equal to: 100-20=80

And final;
20+(80*(250/1000)) =
20+(80*0.25) =
20+20=
40

In this code, final number can't be smaller than rmin, and can't be bigger than rmax. And we can give float number or under zero numbers.

And finally, it's our class;

#include <stdlib.h>
#include <iostream> 
using namespace std;

class randomengine{
    public:
    int r;
    double d,s;
    void init(){srand(time(0));}
    double number(double rmax,double rmin){
        r=rand();
        d=rmax-rmin;
        s=rmin+(d*(float)r/RAND_MAX);
        return s;
        }
    };
randomengine rnd;

int main ()
{
    rnd.init();
    cout<<(int)rnd.number(20,100)<<endl;
    cout<<rnd.number(0.5,0.8);
    return 0;
}

Again sorry for bad english..

No comments:

Post a Comment