473,289 Members | 1,929 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

Question about random generator.

mdh
Hi Group,
Followed the faq to generate random numbers within a given range, so
used this:
# include <stdlib.h>
# define ULIMIT 100
int(........)

intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));
Perhaps I have not run the function enough, but each time, intarr[0]
equals 0. The subsequent numbers are "random" or "psuedo-random" as I
would expect, but I cannot explain element '0'. Have I just not run it
enough? Or is there another explanation.

Thanks in advance.

Jun 2 '06 #1
15 1929
"mdh" <md**@comcast.net> writes:
Hi Group,
Followed the faq to generate random numbers within a given range, so
used this:
# include <stdlib.h>
# define ULIMIT 100
int(........)

intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));
Perhaps I have not run the function enough, but each time, intarr[0]
equals 0. The subsequent numbers are "random" or "psuedo-random" as I
would expect, but I cannot explain element '0'. Have I just not run it
enough? Or is there another explanation.


The explanation is in the rest of the code, which you didn't post.

If you'll show us a complete self-contained program, we migh be able
to help. Otherwise, we can't do more than guess.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 2 '06 #2
mdh
Keith Thompson wrote:

The explanation is in the rest of the code, which you didn't post.

If you'll show us a complete self-contained program, we migh be able
to help. Otherwise, we can't do more than guess.


Ok....I am going through K&R, and trying to get my head around Shell
Sorts. Wanted to generate random numbers for my "presorted" array,
"intarr". But just using rand() gave me such big numbers, hard to get
my head around it. Hence this formula. The rest of the function deals
with the sort, and does not effect intarr. ( I think).
#include <stdio.h>
# include <stdlib.h>
# define NELEMENTS 1000
# define UBOUND NELEMENTS-1
# define ULIMIT 100


int main (){

int intarr[NELEMENTS], v[NELEMENTS], i, j;

for (i=0; i <=UBOUND; i++)
intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));

j=i=0;
while ( j<= UBOUND)

v[j++] = intarr[i++];

Jun 2 '06 #3
"mdh" <md**@comcast.net> writes:
Keith Thompson wrote:
The explanation is in the rest of the code, which you didn't post.

If you'll show us a complete self-contained program, we migh be able
to help. Otherwise, we can't do more than guess.


Ok....I am going through K&R, and trying to get my head around Shell
Sorts. Wanted to generate random numbers for my "presorted" array,
"intarr". But just using rand() gave me such big numbers, hard to get
my head around it. Hence this formula. The rest of the function deals
with the sort, and does not effect intarr. ( I think).
#include <stdio.h>
# include <stdlib.h>
# define NELEMENTS 1000
# define UBOUND NELEMENTS-1
# define ULIMIT 100


int main (){

int intarr[NELEMENTS], v[NELEMENTS], i, j;

for (i=0; i <=UBOUND; i++)
intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));

j=i=0;
while ( j<= UBOUND)

v[j++] = intarr[i++];


This is still incomplete. Where's the rest of the program?

rand() always generates the same sequence given the same starting
point. Use srand() to specify a different starting point. See the
FAQ for details. I don't know if that's the problem.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 2 '06 #4
mdh
Keith Thompson wrote:
This is still incomplete. Where's the rest of the program?

Ok...here is the entire program. The reason I am not using a subroutine
is to be able to step through it and watch what happens...I know the
structure below is not ideal.

#include <stdio.h>
# include <stdlib.h>
# define NELEMENTS 1000
# define UBOUND NELEMENTS-1
# define ULIMIT 100
void shellsort( int v[], int n);

int main (){

int intarr[NELEMENTS], v[NELEMENTS], i, j;

for (i=0; i <=UBOUND; i++)
intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));

j=i=0;
while ( j<= UBOUND)

v[j++] = intarr[i++];
/* shellsort(intarr2, NELEMENTS-1); */

int gap, k, l, temp, z ;

for (gap=UBOUND/2; gap>0; gap /=2)

for (k=gap; k <= UBOUND; k++)

for ( l=k-gap; l >=0 && v[l] > v[l+gap]; l -= gap) {

temp=v[l];
v[l]=v[l+gap];
v[l+gap]=temp;

}
int m;

printf("%20s %20s %20s\n\n\n", "Arr Subscript","Presorted", "Sorted");

for (z=m=0; m<=UBOUND; m++,z++)

printf("%10d %30d %20d\n", z ,intarr[m], v[m]);



return 0;
}
/************/

void shellsort( int v[], int n){

int gap, i, j, temp;

for (gap=n/2; gap>0; gap /=2)

for ( i=gap; i < n; i++)

for ( j=i-gap; j >=0 && v[j] > v[j+gap]; j -= gap) {

temp=v[j];
v[j]=v[j+gap];
v[j+gap]=temp;

}

}

Jun 2 '06 #5
mdh wrote:
Hi Group,
Followed the faq to generate random numbers within a given range, so
used this:
# include <stdlib.h>
# define ULIMIT 100
int(........)

intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));
Perhaps I have not run the function enough, but each time, intarr[0]
equals 0. The subsequent numbers are "random" or "psuedo-random" as I
would expect, but I cannot explain element '0'. Have I just not run it
enough? Or is there another explanation.


It seems that that is the sequence of your particular rand()
implementation. Trying seeding rand() with srand(time(NULL)). Then see
if intarr[0] still contains a zero.

Jun 2 '06 #6
mdh
santosh wrote:
It seems that that is the sequence of your particular rand()
implementation. Trying seeding rand() with srand(time(NULL)). Then see
if intarr[0] still contains a zero.


Tks Santosh...I guess I am not completely familiar with the notion of
seeding rand. Is there a ref to this in the FAQ? Or, is this something
that can be explained briefly?

Jun 2 '06 #7
mdh wrote:
santosh wrote:
It seems that that is the sequence of your particular rand()
implementation. Trying seeding rand() with srand(time(NULL)). Then see
if intarr[0] still contains a zero.


Tks Santosh...I guess I am not completely familiar with the notion of
seeding rand. Is there a ref to this in the FAQ? Or, is this something
that can be explained briefly?


Look up question 13.17 at http://c-faq.com/

The idiomatic way is, as I explained previously, to pass the return
value of the time() function, to srand() after casting it to an
unsigned integer.

Jun 2 '06 #8
mdh
santosh wrote:
The idiomatic way is, as I explained previously, to pass the return
value of the time() function, to srand() after casting it to an
unsigned integer.


thank you Santosh.

Jun 2 '06 #9
santosh said:
mdh wrote:
santosh wrote:
> It seems that that is the sequence of your particular rand()
> implementation. Trying seeding rand() with srand(time(NULL)). Then see
> if intarr[0] still contains a zero.


Tks Santosh...I guess I am not completely familiar with the notion of
seeding rand. Is there a ref to this in the FAQ? Or, is this something
that can be explained briefly?


Look up question 13.17 at http://c-faq.com/

The idiomatic way is, as I explained previously, to pass the return
value of the time() function, to srand() after casting it to an
unsigned integer.


This can fail if the value returned by time() is not expressible as an
unsigned int, cast or no cast.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 2 '06 #10
Richard Heathfield wrote:
santosh said:
mdh wrote:
santosh wrote:

> It seems that that is the sequence of your particular rand()
> implementation. Trying seeding rand() with srand(time(NULL)). Then see
> if intarr[0] still contains a zero.

Tks Santosh...I guess I am not completely familiar with the notion of
seeding rand. Is there a ref to this in the FAQ? Or, is this something
that can be explained briefly?


Look up question 13.17 at http://c-faq.com/

The idiomatic way is, as I explained previously, to pass the return
value of the time() function, to srand() after casting it to an
unsigned integer.


This can fail if the value returned by time() is not expressible as an
unsigned int, cast or no cast.


Yes. Thats why I provided a link to the FAQs, which, presumably, the OP
will read before writing his code.

Jun 2 '06 #11
mdh

Richard Heathfield wrote:

This can fail if the value returned by time() is not expressible as an
unsigned int, cast or no cast.

This is what I have now used.....it seems to do the trick....is this
how others would do it?

<Same code as above>

srand((unsigned int)time((time_t *)NULL));

for (i=0; i <=ubound; i++)

intarr[i]= ( rand()/(RAND_MAX/ULIMIT+1));
etc etc

Jun 2 '06 #12
santosh said:
Richard Heathfield wrote:
santosh said:
> The idiomatic way is, as I explained previously, to pass the return
> value of the time() function, to srand() after casting it to an
> unsigned integer.


This can fail if the value returned by time() is not expressible as an
unsigned int, cast or no cast.


Yes. Thats why I provided a link to the FAQs, which, presumably, the OP
will read before writing his code.


Until not so terribly long ago, a guy called Lawrence Kirby was a regular
contributor to comp.lang.c - Lawrence's knowledge of C was quite
astounding, and he was a decent bloke too. Never got into fights, never
raised a hand to anyone, just poured out his C knowledge on the group
whenever it was needed. Wonderful chap. I do hope he returns soon.

He once posted an srand-initialising routine, to maximise the entropy
available from time() without invoking potentially undefined behaviour:

#include <stddef.h>
#include <time.h>
#include <limits.h>

/* Usage: srand (time_seed ()); */

/* Choose and return an initial random seed based on the current time. */

unsigned
time_seed (void)
{
time_t timeval;
unsigned char *ptr;
unsigned seed;
size_t i;

timeval = time (NULL);
ptr = (unsigned char *) &timeval;

seed = 0;
for (i = 0; i < sizeof timeval; i++)
seed = seed * (UCHAR_MAX + 2U) + ptr[i];

return seed;
}

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 2 '06 #13
Richard Heathfield wrote:
santosh said:
Richard Heathfield wrote:
santosh said:

> The idiomatic way is, as I explained previously, to pass the return
> value of the time() function, to srand() after casting it to an
> unsigned integer.

This can fail if the value returned by time() is not expressible as an
unsigned int, cast or no cast.


Yes. Thats why I provided a link to the FAQs, which, presumably, the OP
will read before writing his code.


Until not so terribly long ago, a guy called Lawrence Kirby was a regular
contributor to comp.lang.c - Lawrence's knowledge of C was quite
astounding, and he was a decent bloke too. Never got into fights, never
raised a hand to anyone, just poured out his C knowledge on the group
whenever it was needed. Wonderful chap. I do hope he returns soon.

He once posted an srand-initialising routine, to maximise the entropy
available from time() without invoking potentially undefined behaviour:

#include <stddef.h>
#include <time.h>
#include <limits.h>

/* Usage: srand (time_seed ()); */

/* Choose and return an initial random seed based on the current time. */

unsigned
time_seed (void)
{
time_t timeval;
unsigned char *ptr;
unsigned seed;
size_t i;

timeval = time (NULL);
ptr = (unsigned char *) &timeval;

seed = 0;
for (i = 0; i < sizeof timeval; i++)
seed = seed * (UCHAR_MAX + 2U) + ptr[i];

return seed;
}


Okay, it extracts timeval's component bytes, implicitly converting them
to unsigned int. Just a question. Why is 2 being added to UCHAR_MAX?
And what if sizeof (char) == sizeof (int)? Would the function be
equally useful then, as far as increasing the entropy of timeval is
concerned?

Jun 2 '06 #14
santosh said:
Richard Heathfield wrote:

<Lawrence Kirby's time_seed() function)
#include <stddef.h>
#include <time.h>
#include <limits.h>

/* Usage: srand (time_seed ()); */

/* Choose and return an initial random seed based on the current time. */

unsigned
time_seed (void)
{
time_t timeval;
unsigned char *ptr;
unsigned seed;
size_t i;

timeval = time (NULL);
ptr = (unsigned char *) &timeval;

seed = 0;
for (i = 0; i < sizeof timeval; i++)
seed = seed * (UCHAR_MAX + 2U) + ptr[i];

return seed;
}
Okay, it extracts timeval's component bytes, implicitly converting them
to unsigned int. Just a question. Why is 2 being added to UCHAR_MAX?


To give you a number of the form 2^n + 1, which, empirically speaking, is
quite a good form to use when hashing a series of bytes into an individual
value.
And what if sizeof (char) == sizeof (int)?


In such a circumstance, admittedly, the hashing is less good! :-) In such a
case, you might want to multiply by, say, (UCHAR_MAX - 1) / 2 + 2 instead.
Or maybe even (UCHAR_MAX - 3) / 4 + 2.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 2 '06 #15
Richard Heathfield <in*****@invalid.invalid> writes:
santosh said:
Richard Heathfield wrote:

<Lawrence Kirby's time_seed() function)
Okay, it extracts timeval's component bytes, implicitly converting them
to unsigned int. Just a question. Why is 2 being added to UCHAR_MAX?


To give you a number of the form 2^n + 1, which, empirically speaking, is
quite a good form to use when hashing a series of bytes into an individual
value.


In particular, n is usually 8, so UCHAR_MAX + 2 is usually 257,
which is prime.
--
"IMO, Perl is an excellent language to break your teeth on"
--Micah Cowan
Jun 2 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Brandon Michael Moore | last post by:
I'm trying to test a web application using a tool written in python. I would like to be able to generate random values to put in fields. I would like to be able to generate random dates (in a...
28
by: Paul Rubin | last post by:
http://www.nightsong.com/phr/python/sharandom.c This is intended to be less predicable/have fewer correlations than the default Mersenne Twister or Wichmann-Hill generators. Comments are...
23
by: hedylogus | last post by:
I've just begun learning C++ and I'm trying to write a program to shuffle a deck of cards. I've succeeded....for the most part....but every now and then rand() produces duplicate random numbers...
4
by: Wahoo | last post by:
Another question,my teacher gave me a code for generate a random number from 1 - range, but I can't made it work, where is the problem? Thanks!!
3
by: Joe | last post by:
Hi, I have been working on some code that requires a high use of random numbers within. Mostly I either have to either: 1) flip a coin i.e. 0 or 1, or 2) generate a double between 0 and 1. I...
6
by: Starbuck | last post by:
Hi In VB6 we used the following to create a unique random number - Function longSerial() As Long longSerial = Val((Format$(Int(Rnd * 424) - 212)) + Format$((Timer * 100), "0000000"))...
5
by: Peteroid | last post by:
I know how to use rand() to generate random POSITIVE-INTEGER numbers. But, I'd like to generate a random DOUBLE number in the range of 0.0 to 1.0 with resolution of a double (i.e., every possible...
104
by: fieldfallow | last post by:
Hello all, Is there a function in the standard C library which returns a prime number which is also pseudo-random? Assuming there isn't, as it appears from the docs that I have, is there a...
2
by: Matthew Wilson | last post by:
The random.jumpahead documentation says this: Changed in version 2.3: Instead of jumping to a specific state, n steps ahead, jumpahead(n) jumps to another state likely to be separated by many...
11
TTCEric
by: TTCEric | last post by:
This will be original. I promise. I cannot get the random number generator to work. I tried seeding with Date.Now.Milliseconds, it still results in the same values. What I have are arrays...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.