0

I have a problem with the rand() function. I would like to randomly generate eps values, different one from each other for i=0,...,VOL. However, when I print eps, it is always the same. Could you please tell what it is wrong in my code? Thank you.

    ...
    #include <time.h>
    ...

    void function(...);

    int main(){

    function();

    return 0;
    }

    void function(...){

    srand((unsigned int)time(NULL));
    ...

    for(i=0;i<VOL;i++){

            signal1[i]=0.; // No signal

            eps=rand()/(RAND_MAX+0.5);

            if(signal1[i]==(MIN+MAX)){ 

                net[i]= 0; 

                exp[i]=a+eps; 
                printf("eps: %f\n", eps);

            } 
    }
    }

The full part of the code (to copy the entire code is impossible as it is very long) is:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define VOL 15

#define MAX 10
#define MIN 0

float random_sign_high[VOL]={2,2,2,2,2,2,2,2,2,1,1,1,1,1,0};
float random_sign_low[VOL]={2,2,2,2,2,2,2,2,1,1,1,1,1,0,0};

void function();

int main(){

function();

return 0;
}

void function(){
...
srand((unsigned int)time(NULL));

for(i=0;i<VOL;i++){

        signal1[i]=0.; // No signal
        signal2[i]=0.; // No signal


        if(H_PR!=0){
             shuffle_signals(random_sign_high);
        }

        if(L_PR!=0){
            shuffle_signals(random_sign_low);
        }

        eps=rand()/(RAND_MAX+0.5);
        printf("eps: %f\n", eps);

        if(tot_sig==(MIN+MAX)){

            net[i]= 0;

            exp_p[i]=a+eps;

        }

and the shuffle function is:

double shuffle_signals(float array[VOL])

{
    srand((unsigned int) time(NULL));

    if(VOL>1)
    {
        int i,j,t;
        for(i=0; i<VOL;i++)
        {
            j=i+rand()/((float)RAND_MAX/(VOL-i)+1.);
            t=array[j];
            array[j]=array[i];
            array[i]=t;

            if(array[i]==1){
                signal2[i]=MIN;
                signal1[i]=MAX;
            }
            else if(array[i]==0){
                signal2[i]=MIN;
                signal1[i]=MIN;
            }
            else if (array[i]==2){
                signal1[i]=MAX;
                signal2[i]=MAX;
            }
            tot_sig= signal1[i]+signal2[i];
        }
        // printf("tot_sign: %lf\n", tot_sig);
    }
    return tot_sig;
}

}

The other parts are irrelevant. You can think 'a' be a constant, H_PR=0.5 and L_PR=0.1 Thanks a lot.

  • Try removing the `(unsigned int)` from in front of the `time(NULL)`? – Rivasa Oct 13 '17 at 23:13
  • Thank you, Annabelle. Unfortunately, I tried to remove (unsigned int) from in front of the time(NULL), but eps is always the same. I have no idea where my error is. –  Oct 13 '17 at 23:15
  • Can you please include the full code, or strip out the irrelevant parts further? As it is now, I can't compile it to test. Since a lot of variables aren't defined. – Rivasa Oct 13 '17 at 23:19
  • Any time you compare a float using `==` then your code is wrong. – stark Oct 13 '17 at 23:24
  • 2
    _Could you please tell what it is wrong in my code?_ It does not compile. Get it to compile first, then step through with a debugger. With the code in its current state, its not easy to know what you want to do. – ryyker Oct 13 '17 at 23:30
  • Thank you, stark. I've just changed the type of tot_sig, but eps is always the same. –  Oct 13 '17 at 23:31
  • What type is eps ? Judging from the printf() call it is some kind of float, but I cannot se the declaration – user1048576 Oct 13 '17 at 23:39
  • the function: `function()` is: 1) being prototyped to allow any number (including 0) parameters of any type. Suggest the prototype be: `void function( void );` 2) the posted code is missing the end of the function body. – user3629249 Oct 13 '17 at 23:57
  • regarding: `j=i+rand()/((float)RAND_MAX/(VOL-i)+1.);` the `1.` had type `double` perhaps it would be better to define it correctly as: `1.f` – user3629249 Oct 14 '17 at 00:03
  • for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest using 4 spaces for each indent level. 2) use appropriate horizontal spacing inside parens, around C operators, after semicolons, after commas. – user3629249 Oct 14 '17 at 00:06
  • when compiling, always enable the warnings, then fix those warnings. (for `gcc`, at a minimum use: `-Wall -Wextra -pedantic -Wconversion -std=gnu11` ) – user3629249 Oct 14 '17 at 00:12
  • the array `array[]` is a `float` type. comparing the values to integer numbers, like 1, 2, is not a good idea. Many integer values cannot be exactly represented in `float`. Instead compare to `float` values, like 1.0f, 2.0f – user3629249 Oct 14 '17 at 00:14
  • the arrays: `signal1[]` and `signal2[]` are not defined anywhere in the posted code. – user3629249 Oct 14 '17 at 00:17
  • This is a duplicate of [`srand()` — why call it only once?](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/) — but I used my vote to close as there wasn't an MCVE so I can't close it as a duplicate too. – Jonathan Leffler Oct 14 '17 at 01:10

3 Answers3

2

You're calling shuffle_signals() repeatedly from inside a loop. Each time you visit this function, you call srand(), which resets the random number generator based on the current time (seconds since 1970). You should only call srand() once in your program. Somewhere near the top of main() would be a good place to do it.

r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • Thank you, @squeamish ossifrage. As you suggested, eps is different. However, I lost information about my random_sign_high and low. In fact, the number of elements with MAX and MIN is not always that one I have fixed at the beginning. How can I solve it? I have one more question: if I use rand() into more functions, can I call srand() in each of them or just in main()? –  Oct 13 '17 at 23:56
  • *"... the number of elements with MAX and MIN is not always that one I have fixed at the beginning."* — I have no idea what you mean by this. It doesn't matter how many functions you use `rand()` in. **Unless you want to receive the same sequence of numbers again, you should only call `srand()` once. I suggest you do this somewhere near the top of `main()`.** – r3mainer Oct 14 '17 at 00:02
1

the function: shuffle_signals() is recursive, However, the function: srand() should be called only once in the whole program. Suggest moving the call to srand() to early in the main() function.

user3629249
  • 16,402
  • 1
  • 16
  • 17
0

You can do that:

int main ()
{
    int x;
    x = rand() % 100; // here you got always the same value
    printf ("Our first number: %d\n", x);
    srand ( time(NULL) ); // from now on you'll get random values
    x = rand() % 100;
    printf ("Some random number: %d\n", x);
    x = rand() % 100;
    printf ("The first number again: %d\n", x);

    return 0;
}

There's nothing affects random values in when adding unsigned int in srand(unsigned int(time(NULL))) so you can add it or leave it the result is ok.

Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • Although keep in mind that time() returns the number of *seconds* since the epoch, so if you rerun the program quickly enough, it'll generate the same seed both times. – Ray Oct 13 '17 at 23:43