Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Random Integer
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
zero-impact




PostPosted: Fri Jun 20, 2008 10:42 am   Post subject: Random Integer

Hi I'm wanting to learn C as a next step from a course in turing. I would say i am fairly competent in turing but during the summer i want to move on to something different.
My question is, is their an equivalent to turings Rand.Int (min,max) in C? i have read about rand () and srand () but i am still unable to find a function that would allow me to specify a starting number and a maximum number.
Is their anyway i could do that with built in functions or what else would i have to do?
Thanks for any help


I don't know if this should be in the C section or the Turing section sorry :S
Sponsor
Sponsor
Sponsor
sponsor
richcash




PostPosted: Fri Jun 20, 2008 12:17 pm   Post subject: Re: Random Integer

I don't know C but supposedly rand() returns a random integer from 0 to RAND_MAX. So, you have to get the value of RAND_MAX (which should be in the same module as rand(), I think it's stdlib.h) and then do some math. If you want the random integer to go from 0 to n, then do something like :
C:
rand() / (RAND_MAX / (n + 1))

And it's not hard to convert that to a function that takes a minimum an maximum. You get a random number from 0 to (maximum - minimum) and then add minimum.
apomb




PostPosted: Fri Jun 20, 2008 12:18 pm   Post subject: Re: Random Integer

Hey, why not take a look at the stickys in the Turing forum for the answer to the Where To Go Next question. as for the random integer in C, you would have something like:
code:
#include <stdlib.h>
#include <time.h>
#define TRUE     1
#define FALSE    0

void shuffle( int *deck, int n_cards )
{
        int     i;
        static  int       first_time = TRUE;

        /*
        ** Seed the random number generator with the current time
        ** of day if we haven't done so yet.
        */
        if( first_time ){
                first_time = FALSE;
                srand( (unsigned int)time( NULL ) );
        }

        /*
        ** "Shuffle" by interchanging random pairs of cards.
        */
        for( i = n_cards - 1; i > 0; i -= 1 ){
                int     where;
                int     temp;

                where = rand() % i;
                temp = deck[ where ];
                deck[ where ] = deck[ i ];
                deck[ i ] = temp;
        }
}

which simulates the shuffling of a deck of cards, now this is where learning comes in to play to figure out how this program implements the random numbers and how you can take it and use it for yourself.
richcash




PostPosted: Fri Jun 20, 2008 12:49 pm   Post subject: Re: Random Integer

If I understand correctly, that will not provide an even distribution of randomness unless RAND_NUM is a factor of i, right? All numbers below RAND_NUM%i will have a slightly higher probability than all numbers above RAND_NUM%i. Since i is very small in comparison to RAND_NUM, this skewed distribution is unnoticeable in this case, but if you are randomizing within a large range it might become noticeable.
md




PostPosted: Fri Jun 20, 2008 12:53 pm   Post subject: RE:Random Integer

rand() returns a random integer; I've never heard of RAND_NUM but if it exists I would assume it's 65535.

And no, it won't effect the distribution to use modulus - as you end up with random numbers in the range of 0-(i-1) only.
richcash




PostPosted: Fri Jun 20, 2008 1:03 pm   Post subject: Re: Random Integer

md wrote:

rand() returns a random integer; I've never heard of RAND_NUM but if it exists I would assume it's 65535.

And no, it won't effect the distribution to use modulus - as you end up with random numbers in the range of 0-(i-1) only.

Maybe I don't quite get it, but what if I want to randomize from 0 to 65534 (assuming RAND_NUM is 65535). The probability of getting 0 or 1 is twice as likely as getting any other number, right? Obviously it is unnoticeable for most realistic ranges, though.

EDIT - I just found this article, and it seems to agree with using division instead of modulus.
btiffin




PostPosted: Fri Jun 20, 2008 2:13 pm   Post subject: Re: Random Integer

Old guy ramble follows;
richcash's article link is good. There are deeper explanations and I'll bet there are a few books floating around the offices near apomb and jeffgreco13 that are 2,000 pages thick and discuss nothing but the dangers of "psuedo" in psuedo-random. Smile

Only piping up so people reading this aren't led too far astray. It's RAND_MAX not RAND_NUM and you should find it in stdlib.h. For my box it's 2^31 - 1 and it's guaranteed to be no less than 2^15 - 1

For more details about stats and randoms check the R programming language at http://cran.r-project.org/
Or for a true random number off the net, check out http://random.org
Quote:
The random.org web service samples atmospheric noise via radio tuned to an unused broadcasting frequency together with a skew correction algorithm due to John von Neumann.
Ahh, John von; my favourite Quantum Mechanic.

Cheers
Vermette




PostPosted: Fri Jun 20, 2008 2:19 pm   Post subject: Re: Random Integer

btiffin @ June 20th 2008, 14:13 wrote:
Old guy ramble follows;
richcash's article link is good. There are deeper explanations and I'll bet there are a few books floating around the offices near apomb and jeffgreco13 that are 2,000 pages thick and discuss nothing but the dangers of "psuedo" in psuedo-random. Smile

Only piping up so people reading this aren't led too far astray. It's RAND_MAX not RAND_NUM and you should find it in stdlib.h. For my box it's 2^31 - 1 and it's guaranteed to be no less than 2^15 - 1

For more details about stats and randoms check the R programming language at http://cran.r-project.org/
Or for a true random number off the net, check out http://random.org
Quote:
The random.org web service samples atmospheric noise via radio tuned to an unused broadcasting frequency together with a skew correction algorithm due to John von Neumann.
Ahh, John von; my favourite Quantum Mechanic.

Cheers


The Soviets were big fans of using dishes pointed at space to generate onetime encryption pads for their diplomatic communiques. However they knew to change up the frequencies as certain political enemies could point their transmitters at those dishes and blast it with noise to produce a more 'predictable' pattern. Smile
Sponsor
Sponsor
Sponsor
sponsor
richcash




PostPosted: Fri Jun 20, 2008 3:18 pm   Post subject: Re: Random Integer

btiffin @ Fri Jun 20, 2008 2:13 pm wrote:
It's RAND_MAX not RAND_NUM and you should find it in stdlib.h

Oops, thanks btiffin. Sorry for the confusion.
btiffin




PostPosted: Fri Jun 20, 2008 4:20 pm   Post subject: Re: Random Integer

richcash; Bah, I rarely care. Pseudo-random is like Newtonian physics. Don't really care that it is "wrong" when it gets it so close to right that it's useful.

I only know a little about it as I got bit once. Hashing phone numbers for the phone company, the algorithm included some poorly chosen randomness. npa-nxx-nnnn phone numbers were grouping due to the low order bit distribution issue and seeds that influenced that distribution. One morning our runtime slowed to a crawl. My algorithm had put 90% of the keys into very unevenly distributed duplicate slots. Key retrieval was just spinning. One computation code change, a rebuild of the index, and voila; magnitude 4 performance boost.

To be honest; that is the one and only time I've had to care about pseudo-random (but maybe that's because I had been bitten and now know to treat rand and its ilk as voodoo).

Cheers
zero-impact




PostPosted: Sat Jun 21, 2008 1:07 pm   Post subject: Re: Random Integer

apomb @ Fri Jun 20, 2008 12:18 pm wrote:
Hey, why not take a look at the stickys in the Turing forum for the answer to the Where To Go Next question. as for the random integer in C, you would have something like:
code:
#include <stdlib.h>
#include <time.h>
#define TRUE     1
#define FALSE    0

void shuffle( int *deck, int n_cards )
{
        int     i;
        static  int       first_time = TRUE;

        /*
        ** Seed the random number generator with the current time
        ** of day if we haven't done so yet.
        */
        if( first_time ){
                first_time = FALSE;
                srand( (unsigned int)time( NULL ) );
        }

        /*
        ** "Shuffle" by interchanging random pairs of cards.
        */
        for( i = n_cards - 1; i > 0; i -= 1 ){
                int     where;
                int     temp;

                where = rand() % i;
                temp = deck[ where ];
                deck[ where ] = deck[ i ];
                deck[ i ] = temp;
        }
}

which simulates the shuffling of a deck of cards, now this is where learning comes in to play to figure out how this program implements the random numbers and how you can take it and use it for yourself.


Hey thanks for that. I made something exactly like that for a card game in turing and for shuffling other arrays. The only thing i was missing was in turing it would just be where := Rand.Int (lower(array),upper(array))
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 11 Posts ]
Jump to:   


Style:  
Search: