Archived

This topic is now archived and is closed to further replies.

Random numbers

This topic is 5656 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Please I would like to know how can I code a little random number generator function in C, It should be little and capable of generating random numbers from 1 to 32. Is there any tutorial or something similar? Ive been trying but cant get one to work. Thanks "Those who follow the path of the warrior must be ready to die, to stand for their convictions, live for one´s convictions, die for one´s convictions"

Share this post


Link to post
Share on other sites
*sigh* Use the friggin forum search...

#include <stdlib.h>
#include <time.h>
...
//call this once when your program starts.
srand((unsigned int)time(0));
...
int RandNum = int((rand()/(double)RAND_MAX)*31)+1;
...

That might work.

Later,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links


[edited by - zealouselixir on June 23, 2002 2:26:28 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Tai-Pan
Please I would like to know how can I code a little random number generator function in C, It should be little and capable of generating random numbers from 1 to 32. Is there any tutorial or something similar? Ive been trying but cant get one to work.

Is this a learning project, or do you need a random number generator? There''s one in the Standard Library (rand), as well as several publicly available random numbers with higher periods and better distribution (Mersienne Twister comes to mind).

If it is a learning process, realize that it is difficult to generate true randomness. The RNGs referred to above are actually all pseudo-random number generators (the sources are generally available; Google it). Some suggest using something like a radio antenna set to static and sampling at oscillating intervals, but that is probably overkill for your needs.

Share this post


Link to post
Share on other sites

  
#include <mmsystem.h>

int GetRandNumber(int low, int high)
{
int temp = 0;
srand((int)timeGetTime());
high = high - low;
temp = rand()%high;
temp += low;
return temp;
}

This should work, i.e.
GetRandNumber(1, 32) will give you a number between 1 and 32

Share this post


Link to post
Share on other sites
quote:
Original post by ZealousElixir
int RandNum = int((rand/(double)RAND_MAX)*31)+1;



Sorry, but this cast is C++ (won't work in C) and "rand" only gives the linker point for the function


// edit - nix the second bit - as you added the () ...



[edited by - lessbread on June 23, 2002 2:29:47 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Oluseyi
I wonder if you realize that he said code an RNG?


Yes, as a matter of fact, I did. What''s your point?

http://www.gamedev.net/community/forums/topic.asp?topic_id=96406
http://www.gamedev.net/community/forums/topic.asp?topic_id=39324
http://www.gamedev.net/community/forums/topic.asp?topic_id=47804
http://www.gamedev.net/community/forums/topic.asp?topic_id=29875

Peace,
Ze.



//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
Thank you people..I just wanted to learn how to code a VERY little function capable of choosing random numbers from 1 to 31..integers of course..thanks for your help.

"Those who follow the path of the warrior must be ready to die, to stand for their convictions, live for one´s convictions, die for one´s convictions"

Share this post


Link to post
Share on other sites
Ive been reading something..but I dont understand what the "seed" is.

"Those who follow the path of the warrior must be ready to die, to stand for their convictions, live for one´s convictions, die for one´s convictions"

Share this post


Link to post
Share on other sites
The seed is at the core (no pun intended) of the whole pseudorandomness issue. It is basically an arbitrary number off which calculations for randomness are based. With most "RNG"s, you can specify the same seed and get the same series of values as output. This is useful for debugging and demo saving. The value of the seed isn''t critical, as long as it''s reasonably unpredictable; this is why most people "seed" srand with the system time or some other high-precision, volatile value.

Later,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
quote:
Original post by Tai-Pan
...code a little random number generator function in C, It should be little and capable of generating random numbers from 1 to 32


A little one:

unsigned rnd(unsigned max)
{
return time(NULL) % max + 1;
}
...
int main()
{
...
rnd_num = rnd(32);
...
}


Hope that helps.

[edited by - DerekSaw on June 24, 2002 1:50:18 AM]

Share this post


Link to post
Share on other sites
Ensure that you only seed the random number once in your program, before making all the random numbers.

If you seed rand with the same number, you'll get the same sequence of random numbers.

This is why seeding with a low resolution timer isn't a good idea, as you may get the same seed twice if your seed function gets called again at approximately the same time.

Edit - Don't generate random numbers using the "time" function as illustrated above. What you'll get instead is a slowly incrementing counter.


Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions


[edited by - siaspete on June 24, 2002 2:23:05 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster

  
#include <mmsystem.h> // must also link winmm.lib


...

unsigned int random_number(int min, int max)
{
static unsigned int seed = timeGetTime();

seed += 653; // add a number that you made up.

seed *= 2; // multiply by 2

seed %= 10000; // keep it below 10,000.


return ((seed % (max-min)) + min);
}


Pretty crap numbers outputted, but ultimately does the job.

Share this post


Link to post
Share on other sites
quote:
Original post by siaspete

Edit - Don''t generate random numbers using the "time" function as illustrated above. What you''ll get instead is a slowly incrementing counter.



ooops.. forgot to mention that. The function I shown is just ''raw'' and you should call the function few seconds at a time.... because time() (in most cases) increase by one for each second tick.

Share this post


Link to post
Share on other sites
Sort of not much use but..

I programmed a simple random number generator on a PIC microcontroller. I recall that I simply chose a seed based on the microcontrollers internal counter, then OR'd two bits together, and added the result as the MSB of the byte after shifting the byte right once. Once I reached the end of the random number sequence, I simply reset the seed with whatever value was in the internal counter again.

And to add to it slightly, I saved the seed value to the eeprom so that upon a restart the number sequence was still semi random.

By using the counter as the seed and relying on user input, it greatly increases the chance of the numbers 'looking' random. Of course, by knowing the seed value and the formula, it is of course easy to predict the sequence.


Here's the code, not that I think it'll be muuch help to anyone, but it might be remotely interesting...

  
;-------------------------------------------------------------------------------------------------------------------
; Creates a 4 bit random number. The random number is different every time the PIC is reset.
;
; AUTHOR: David Stubbs
; GLOBALS: Seed
; Rannum
;-------------------------------------------------------------------------------------------------------------------
Random

bcf STATUS, RP0 ; Move into bank 0

movlw SEED_ADDRESS
movwf EEADR ; Set address to read from EEPROM

bsf STATUS, RP0 ; Move into bank 1
bsf EECON1, RD ; EE = Read
bcf STATUS, RP0 ; Move into bank 0
movf EEDATA, w ; W = EEDATA

;if seed = F then reset seed

movf Seed, 0 ; Move seed to W
andlw b'00001111' ; Disregard top bits
xorlw 0xF ; Test if F
btfsc STATUS, Z
goto InitSeed ; If not do random routine

movf Seed, 0 ; Move seed to W
andlw b'00001111' ; Disregard top bits
xorlw 0 ; Test if F
btfsc STATUS, Z
goto InitSeed ; If not do random routine

goto DoRandom

InitSeed

movf TMR0, W ; If at end of rand sequence set seed to
movwf Seed ; The timer value to give a different set
; of random numbers

DoRandom

rlf Seed, 1 ; Rotate left 1 bit

movf Seed, 0 ; Move Seed into w reg

bcf Seed, 0
btfsc Seed, 4 ; A OR B = 0 only if A = 0 and B = 0
bsf Seed, 0 ; So if byte 7 and 4 are 0 set byte 0 to 0
btfsc Seed, 7 ; Otherwise set it to 1
bsf Seed, 0

movf Seed, 0 ; Move seed to w
bcf STATUS, RP0 ; Bank 0 for EEDATA
movwf EEDATA ; Copy seed to EEDATA
movlw SEED_ADDRESS ; Set address in EEPROM to write to
movwf EEADR

bsf STATUS, RP0 ; Move into bank 1
bcf INTCON, GIE ; Disable inetupts
bsf EECON1, WREN ; Enable write
movlw 55h ; Write magic sequence of numbers
movwf EECON2
movlw h'AA'
movwf EECON2
bsf EECON1, WR ; Set WR bit

WaitWrite

btfsc EECON1, WR ; Wait until the seed has
goto WaitWrite ; been writen to the EEPROM

bcf STATUS, RP0 ; Move into bank 0
bsf INTCON, GIE ; Enable ints
bcf EECON1, WREN ; Un-enable write

movf Seed, W
andlw b'00001111' ; Only want a 4 bit number 0 - f

return


[edited by - n0p3x on June 24, 2002 9:31:08 AM]

Share this post


Link to post
Share on other sites