LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   generating random numbers in C (https://www.linuxquestions.org/questions/programming-9/generating-random-numbers-in-c-378358/)

abk4523 10-30-2005 12:18 PM

generating random numbers in C
 
Just curious. When I created a 5x4 array and filled it with random numbers using the rand() function, I noticed the last number in the row (row 0, column 4) is identical to the first number in the next row (row 1, column 0). Also, each time I run the program, it generates the same numbers when I run the program. Shouldn't the program be generating different numbers?

paulsm4 10-30-2005 12:34 PM

Hmmm - "srand()/rand()" isn't exactly the most sophisticated random number generator in the world, but it *should* work for your purposes.

Please compare what you're doing with this:
Code:

/*
 * rand: Generates 5 numbers using standard "srand()/rand()" function
 *
 * SAMPLE OUTPUT:
 *  rand[0]= 824522256
 *  rand[1]= 1360907941
 *  rand[2]= 1513675795
 *  rand[3]= 1046462087
 *  rand[4]= 253823980
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int
main (int argc, char *argv[])
{
  /* Simple "srand()" seed: just use "time()" */
  unsigned int iseed = (unsigned int)time(NULL);
  srand (iseed);

  /* Now generate 5 pseudo-random numbers */
  int i;
  for (i=0; i<5; i++)
  {
    printf ("rand[%d]= %u\n",
      i, rand ());
  }
  return 0;
}

Your .. PSM

naf 10-30-2005 01:39 PM

Re: generating random numbers in C
 
Quote:

Originally posted by abk4523
Shouldn't the program be generating different numbers?
Random numbers produced by rand() are pseudorandom actually by applying a function with a given index which is incremented each call. The initial random number is always seeded with 1. The program that paulsm4 provided you demonstrates how the srand() modifies the seed by using the system's clock (which should never be the same thing again). If you want improved numbers, make sure you scale rand()'s return value against RAND_MAX using doubles instead of a pure modulus to have a more distributed result. For example (1-10) from the rand manpage:
Code:

j = 1 + (int)( 10.0 * rand() / ( RAND_MAX + 1.0 ) );
As a side note, having repeatable sequence of pseudo-random numbers helps debugging programs that use random numbers by saving the seed used.

primo 10-30-2005 05:49 PM

If you use just time() to get pseudo random numbers and if you run your program many times in a row, then it's predictable that you will have the same sequences.

It's preferable to use gettimeofday() multiplying tv_sec * tv_usec (microseconds).

Wim Sturkenboom 10-30-2005 11:12 PM

Re: generating random numbers in C
 
Quote:

Originally posted by abk4523
I noticed the last number in the row (row 0, column 4) is identical to the first number in the next row (row 1, column 0).
Sounds like a mistake in your design/code. I've never seen it happen that the same number is returned after just a couple of calls to rand.

rel0aded 11-05-2009 04:11 AM

Quote:

Originally Posted by paulsm4 (Post 1927499)
Hmmm - "srand()/rand()" isn't exactly the most sophisticated random number generator in the world, but it *should* work for your purposes.

Please compare what you're doing with this:
Code:

/*
 * rand: Generates 5 numbers using standard "srand()/rand()" function
 *
 * SAMPLE OUTPUT:
 *  rand[0]= 824522256
 *  rand[1]= 1360907941
 *  rand[2]= 1513675795
 *  rand[3]= 1046462087
 *  rand[4]= 253823980
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

--------->int <---------
main (int argc, char *argv[])
{
  /* Simple "srand()" seed: just use "time()" */
  unsigned int iseed = (unsigned int)time(NULL);
  srand (iseed);

  /* Now generate 5 pseudo-random numbers */
  int i;
  for (i=0; i<5; i++)
  {
    printf ("rand[%d]= %u\n",
      i, rand ());
  }
  return 0;
}

Your .. PSM

hello guys.... just asking why do we need to write int before main () cause if i don't dev c++ finds an error...

JohnGraham 11-05-2009 04:16 AM

Quote:

Originally Posted by rel0aded (Post 3745467)
hello guys.... just asking why do we need to write int before main () cause if i don't dev c++ finds an error...

Are you from an C background? In C, any function with no return type specified is assumed to hate a return type of int - in C++, no such assumption is made, and it's a compile-time error to not specify the return value of a function.

John G

wje_lq 11-05-2009 05:03 AM

Quote:

Originally Posted by primo (Post 1927877)
If you use just time() to get pseudo random numbers and if you run your program many times in a row, then it's predictable that you will have the same sequences.

It's preferable to use gettimeofday() multiplying tv_sec * tv_usec (microseconds).

Whatever you use, it's also a good idea to "exclusive OR" that value with your process ID. This covers the situation where you run your program many times in rapid succession.

johnsfine 11-05-2009 07:55 AM

Quote:

Originally Posted by abk4523 (Post 1927475)
I created a 5x4 array

Quote:

I noticed the last number in the row (row 0, column 4) is identical to the first number in the next row (row 1, column 0).
If there are use 4 columns, row 0 column 4 is the same memory location as row 1 column 0. That is how arrays are stored.

4 columns means columns 0 .. 3. There is no column 4.

If you think your 5x4 was 5 columns and 4 rows, I think you are mistaken. Your symptoms say you have 4 columns.

The fact that you are using the array for random numbers just distracted you from an issue that is in the structure of the array itself.

rel0aded 11-05-2009 08:04 AM

Quote:

Originally Posted by JohnGraham (Post 3745470)
Are you from an C background? In C, any function with no return type specified is assumed to hate a return type of int - in C++, no such assumption is made, and it's a compile-time error to not specify the return value of a function.

John G

ye i am trying to write a program in c that checks if 3000 random numbers are powerful and if it finds 10 for expmple to print the %... and i am using dev c++ for writing the program ? :S but in university we don't use int or something else before the main () .. correct me if i am wrong :)

timepasser 11-05-2009 08:20 AM

There is nothing to correct rel0aded. As JohnGraham told you, if you omit the type the compiler will automatically expect an integer to be returned. It is just a good practice to state what type you expect a function to return, thus (most) people declare main as returning int...

rel0aded 11-05-2009 08:47 AM

Quote:

Originally Posted by timepasser (Post 3745697)
There is nothing to correct rel0aded. As JohnGraham told you, if you omit the type the compiler will automatically expect an integer to be returned. It is just a good practice to state what type you expect a function to return, thus (most) people declare main as returning int...

ok i did
Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define COMPUTATIONS 3000
main ()
{int i;
       
        srand(time(NULL));
       
        for (i=0 ; i < COMPUTATIONS ; i++)
  {
    printf ("random_number[%d]= %d\n",i, rand ());
  }
}

without writing int before main ()
and worked :)

smeezekitty 11-05-2009 07:37 PM

Quote:

Originally Posted by wje_lq (Post 3745504)
Whatever you use, it's also a good idea to "exclusive OR" that value with your process ID. This covers the situation where you run your program many times in rapid succession.

who is going to execute the program !1000000! times per second?
i think that is overboard.

wje_lq 11-05-2009 08:16 PM

Quote:

Originally Posted by smeezekitty (Post 3746388)
who is going to execute the program !1000000! times per second?
i think that is overboard.

  1. The inclusion of the pid into the calculation is cheap.
  2. There is a place in hell for programmers who tell themselves, "I won't add this fast, cheap wrinkle to my program because I can't imagine someone ever wanting to do XXX with my program." People come up with new uses for programs, uses which the original designers of the programs often can't possibly imagine.
  3. If there is a security aspect to the program (and it need not be cloak and dagger, it could be as simple as generating moves for some sort of game), then it might not be the legitimate user of the program who does something weird; it could be a hostile user. As soon as you bring hostile users into the mix, you can rely on them pushing the envelope in hitherto unimagined ways.

smeezekitty 11-05-2009 08:45 PM

how can you even call a program 1000000 times per second?
bash, batch and C system and exec calls are all too slow.
the only way you could do it is if its from withen it self and in that case it would have the same PID.

tuxdev 11-05-2009 08:52 PM

640K is enough for anybody.

bartonski 11-06-2009 12:53 AM

Quote:

Originally Posted by smeezekitty (Post 3746449)
how can you even call a program 1000000 times per second?
bash, batch and C system and exec calls are all too slow.
the only way you could do it is if its from withen it self and in that case it would have the same PID.

If you XOR the PID, you don't have to use that type of time resolution.

I can't tell you why, but I like

Code:

seed ( getpid() ^ time() );
better than

Code:

seed( tv_sec * tv_usec (microseconds));
Moore's law ought to knock about 3 orders of magnitude off your safety factor there in 10 years, or 6 in 20. The first line of code will work just as well then as now. The second? I'll take your bet that I can't launch processes that fast in 10 years.

graemef 11-06-2009 02:31 AM

Having looked through the thread it would appear that the answer I was going to give to the original problem has already been given by Johnsfine.

However, the digression on how you seed the random numbers raises a few thoughts. To me I don't like the idea of using the PID because first it is not cross platform. I also like to keep a record of the seed so that the process can be recreated so I tend not to use time() either rather a variable that could be read in or derived (possibly from the time function). But basically if having "random numbers" is a critical element of a program then don't use the rand function but look for a means of getting true random numbers.

Wim Sturkenboom 11-06-2009 02:39 AM

Quote:

Having looked through the thread it would appear that the answer I was going to give to the original problem has already been given by Johnsfine.
johnsfine was a little late :) This thread was started 4 years ago

johnsfine 11-06-2009 07:48 AM

Quote:

Originally Posted by Wim Sturkenboom (Post 3746751)
johnsfine was a little late :) This thread was started 4 years ago

Oops!

I didn't notice the fact that the thread was reopened with a different question, nor the dates on the earlier posts. I just saw that there seemed to be no answer posted for the original question.

I really wish the forum software would give some very visible indication when there is a giant jump in date between two successive posts in a thread.

darthaxul 01-10-2011 04:08 PM

need help
 
this random number program isnt working anyone know what im doing wrong?
Code:

#include <gtk/gtk.h>
#include <glib.h>
 
GRand* g_rand_new (void);
gint number = g_random_int_range (GRand *g_rand_new_with_seed, gint32 3, gint 12);
 
void changer(GtkWidget *widget, gpointer label)
{
 
  sprintf(buf, "%d", number);
  gtk_label_set_text(label, buf);
}
 
int main( int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *label;
  GtkWidget *hitButton;
 
  g_signal_connect(hitButton, "clicked", G_CALLBACK(changer), label);
  gtk_main();
  return 0;
}



All times are GMT -5. The time now is 04:03 AM.