GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 02-Jun-2009, 20:40
alishaikhji alishaikhji is offline
New Member
 
Join Date: Jun 2009
Posts: 3
alishaikhji is on a distinguished road

A float random number in a given range, different everytime function is called


I am working on a program which will need several different integer and float random numbers at different stages, for example:
- At one point, I need a random number (float) in the range 0.1 to 10.0
- At one point, I need a random number (float) in the range 0.5 to 1.5
- At one point, I need a random number (float) in the range 0.3 to 3.0
- At one point, I need a random number (float) in the range 0.1 to 10.0

Also, I need to make it sure that it generates different random numbers everytime each of these functions is called in the program.

For the integer random numbers, rand () is generating the same random number everytime, so I tool help from planet source code's algorithm which is as follows:
CPP / C++ / C Code:
#include <iostream.h>
#include <time.h>
void init_mm( );
int number_range( int from, int to );
int number_mm( void );
static	int	rgiState[2+55]; // leave this alone
int main()


    {
    	init_mm(); //seed the number generator
    	int random = number_range( 0, 1 );
    	cout << random << endl;
}
int number_mm( void )


    {
    int *piState;
    int iState1;
    int iState2;
    int iRand;
    piState		= &rgiState[2];
    iState1	 	= piState[-2];
    iState2	 	= piState[-1];
    iRand	 	= ( piState[iState1] + piState[iState2] )
    			& ( ( 1 << 30 ) - 1 );
    piState[iState1]	= iRand;
    if ( ++iState1 == 55 )
    	iState1 = 0;
    if ( ++iState2 == 55 )
    	iState2 = 0;
    piState[-2]		= iState1;
    piState[-1]		= iState2;
    return iRand >> 6;
}
/*
* Generate a random number.
*/
int number_range( int from, int to )


    {
    int power;
    int number;
    if ( ( to = to - from + 1 ) <= 1 )
    	return from;
    for ( power = 2; power < to; power <<= 1 )
    	;
    while ( ( number = number_mm( ) & ( power - 1 ) ) >= to )
    	;
    return from + number;
}
/*
* This is the Mitchell-Moore algorithm from Knuth Volume II.
*/
void init_mm( )


    {
    int *piState;
    int iState;
    piState	= &rgiState[2];
    piState[-2]	= 55 - 55;
    piState[-1]	= 55 - 24;
    piState[0]	= ( (int) time( NULL ) ) & ( ( 1 << 30 ) - 1 );
    piState[1]	= 1;
    for ( iState = 2; iState < 55; iState++ )


        {
        	piState[iState] = ( piState[iState-1] + piState[iState-2] )
        			& ( ( 1 << 30 ) - 1 );
    }
    return;
}

=========================
when i optimized the code to generate floating random numbers from 0.1 to 10.0 range, it was generating like 1.1, 2.1, 6.1 etc which is not purely random.
Last edited by LuciWiz : 03-Jun-2009 at 02:20. Reason: Please insert your C code between [cpp] & [/cpp] tags
  #2  
Old 03-Jun-2009, 01:02
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,335
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: A float random number in a given range, different everytime function is called


You need to srand() once at the beginning of the program.
__________________

During the election they said Obama could only be elected when pigs fly. Well, we currently have an epidemic of Swine Flu. Coincidence?
  #3  
Old 03-Jun-2009, 11:32
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: A float random number in a given range, different everytime function is called


Quote:
Originally Posted by alishaikhji
...from planet source code's algorithm...
A quick perusal of the code makes me think that the number_mm() function generates values from 0 through through 0x00ffffff. (That's 16,777,215 decimal.)

See Footnote.


It may be usable for your application if you do something like.
CPP / C++ / C Code:
#include <iostream>
#include <iomanip>
using namespace std;

void init_mm();
int number_mm(void);

//
// Put your implementations of init_mm() and number_mm() somewhere in this file
//
double dran(double lower, double upper)
{
    const unsigned int ranmax = 0x00ffffff; //This is for the function you posted
    unsigned int iran = number_mm();
    return lower + (upper - lower)*iran /(ranmax+1.0);
}


int main()
{

    double xran;

    double a = 0.1;
    double b = 10.0;

    double minval = b;
    double maxval = a;
    double sum = 0;

    int n = 1000000; // Generate a million variates

    init_mm();

    cout << fixed;
    for (int i = 0; i < n; i++) {
        xran = dran(a, b);
        if (i < 20) { //Print out the first twenty
            cout << setw(10) << xran;
            if (i % 5 == 4) {
                cout << endl;
            }
        }
        sum += xran;
        if (xran < minval) {
            minval = xran;
        }
        else if (xran > maxval) {
            maxval = xran;
        }
    }
    cout << endl;
    cout << fixed;
    cout << "a      = " << setw(11) << a
         << ", b      = "  << setw(11) << b << endl;
        
    cout << "minval = " << setw(11) << minval
         << ", maxval = " << setw(11) << maxval << endl
         << endl;

    cout << "sum = " << sum << ", average = " << sum/n << endl;

    return 0;
}

Here are a couple of runs:
Code:
9.521356 6.145245 5.666602 1.811847 7.378449 9.090297 6.468746 5.559043 2.027790 7.486833 9.414623 6.901456 6.316078 3.217535 9.433614 2.651149 2.084762 4.635911 6.620674 1.256586 a = 0.100000, b = 10.000000 minval = 0.100002, maxval = 9.999998 sum = 5043320.437102, average = 5.043320
Code:
9.598072 6.269372 5.867444 2.136816 7.904261 9.941078 7.845339 7.786417 5.631756 3.418174 8.949931 2.368105 1.318035 3.586140 4.804176 8.290317 3.094493 1.384810 4.379304 5.664114 a = 0.100000, b = 10.000000 minval = 0.100005, maxval = 9.999999 sum = 5051092.153701, average = 5.051092
...
Quote:
Originally Posted by alishaikhji
it was generating like 1.1, 2.1, 6.1 etc which is not purely random.

What the heck do you mean by "purely random?" Tell us exactly what you would expect to see from three values returned by the function.


Then consider this:
If it generates exactly what you expect, then it is not very random is it? As a matter of fact, I would call that as un-random as you could possibly get.

Let's do a little "thought experiment."

Suppose I shuffle a deck of cards. Now, if you don't know what to expect, then you think it's random. OK?
Now let's suppose that I know exactly what to expect. OK?

I'll open for 20 dollars.


Bottom line: There are lots of tests to determine the "randomness" of an algorithm, but only you can determine whether it is "random enough."


Regards,

Dave

Footnote: Since the code that you posted mentions Knuth, volume II, I will give you a quote from that book:

Quote:
"Many random number generators in use today are not very good.
.
. [a few paragraphs illustrating one for which he had Great Expectations, but that didn't turn out very well]
.
The moral of this story is that random numbers should not be generated with a method chosen at random. Some theory should be used."

Donald E. Knuth
---The Art of Computer Programming
Vol. 2 Seminumerical Algorithms
Last edited by davekw7x : 03-Jun-2009 at 12:02.
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
run script command on ns2.26 newbie06 Computer Software Forum - Linux 65 19-Aug-2009 08:50
Problem executing nam-1.13 RodolfoAlvizu Computer Software Forum - Linux 20 28-Feb-2009 16:23
Would Anyone Like to do This? bradc0101 C Programming Language 0 30-Oct-2006 20:57
Converting a number amount to text Godzilla C++ Forum 5 31-Mar-2006 12:38
Can somebody look at this and point out any errors to me soulfly C Programming Language 7 31-Mar-2004 10:45

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 03:54.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.