This question already has answers here:
rand() generating the same number – even with srand(time(NULL)) in my main!
(7 answers)
Closed 9 years ago.
How do I make my addRandomNumbers() function add different numbers to the array ? Right now it is just adding the same number.
I dont know what i did wrong, I had it outside of the for loop originally and it still generated the same number.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define clear system("cls")
#define pause system("pause")
#define SIZE 5000
#define LB 1 //this is the lower bound
#define UB 500 //this is the upper bound
//Lets Prototype
void addRandomNumbers(int n[]);
void bubbleSort(int n[]);
void displayRandomNumbers(int n[],int c[]);
int main(){
int numbers[SIZE]={0}, counter[SIZE]={0};
addRandomNumbers(numbers);
bubbleSort(numbers);
displayRandomNumbers(numbers,counter);
}
void addRandomNumbers(int n[]){
int i;
for (i=0; i < SIZE; i++){
srand((unsigned)time(NULL));//seed the random number function
n[i] = LB + rand() % (UB - LB + 1 );
}
}
void bubbleSort(int n[]){
int i,temp=0;
for(i=0;i<SIZE-1;i++){
temp=n[i];
n[0]=n[1];
n[i+1]=temp;
}
}
void displayRandomNumbers(int n[], int c[]){
int i;
for(i=0;i<LB;i++)
printf("It is %i\n",n[i]);
pause;
}
If you seed the random number generator with the time, it will keep repeating the same number until the time changes which takes 1 second. Don't do that - seed the generator only once, at the program start.
Only call srand once, at the beginning of the program.
Did you try
srand(time(NULL));
int r = rand();
Related
I'm trying to get an array to be initialized in a function. The initialized array should contain a set of random numbers within a certain range when working as intended. Is this possible in C?
#include <time.h> //time func for seed init
#include <stdlib.h> //srand/rand funcs
#include <stdio.h> //Library for printf function
#define LIMIT 100
void myFunction(int array[], int arrayIndexMaxSize){
for (int index = 0; index < arrayIndexMaxSize; index++){
array[index] = rand() % LIMIT; //Where limit is randomly produced from 0 - Limit inclusive
printf("array[%d] of arrayIndexMaxSize(%d) = %d\n", index, arrayIndexMaxSize, array[index]); //prints out th$
}
}
void main(){
srand(time(0)); //initializes kinda random number generator
int array[50]; //If known at runtime or compile time, must be at block scope meaing inside {curly} braces of any$
myFunction(array, 50);
}
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.
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.
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.
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.
This question already has answers here:
Generate random double number in range [0, 1] in C
(2 answers)
Closed 2 years ago.
I would like to generate a random, real number in the interval [0,1].
I would like to set a pointer, say n, for the number so whenever I stated n, it will be referred to the random generated number.
I have searched on StackOverflow and on Google, but most of them are for C++ or for integers.
I have tried this code suggested to me in the answers:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double n;
double get_random() { return (double)rand() / (double)RAND_MAX; }
n = get_random();
printf("%f", n);
return 0;
}
However, I can only get a value 0.00000000.
How could I fix my program?
You can use:
#include <time.h>
srand(time(NULL)); // randomize seed
double get_random() { return (double)rand() / (double)RAND_MAX; }
n = get_random();
srand() sets the seed which is used by rand to generate pseudo-random numbers. If you don't call srand before your first call to rand, it's as if you had called srand(1) (serves as a default).
If you want to exclude [1] use:
(double)rand() / (double)((unsigned)RAND_MAX + 1);
Full solution:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
double get_random() { return ((double)rand() / (double)RAND_MAX); }
int main()
{
double n = 0;
srand(time(NULL)); // randomize seed
n = get_random(); // call the function to get a different value of n every time
printf("%f\n", n); // print your number
return 0;
}
Every time you run it you will get a different number for n.
This shows how to get random real numbers in the range 0..1 but please note that they are not uniformly distributed. There are only (RAND_MAX+1) discrete values.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int i;
double n;
srand((unsigned)time(NULL)); // seed the random num generator ONCE only
for(i = 0; i < 3; i++) { // get 3 random numbers
n = (double)rand() / RAND_MAX; // in the range 0 ... 1
printf("%f\n", n); // use correct format specifier for the var
}
return 0;
}
My program output:
0.622608
0.814081
0.878689
I can't seem to figure out why this is not working. I am trying to get these two void functions to generate randoms numbers when called in the main. I think the problem has to do with srand(time(NULL)); in the void function's. I think that when it gets called in the main and runs in the for loop, srand(time(NULL)); is not updated so it prints out the same number x times. numGen_10 should generate 1-10 and numGen_4 should generate 1-4 based on a variable.
What can I do to get the functions to output different random numbers each time the function is called?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void numGen_10(int xOry, int* xRey);
void numGen_4(int num, int choice, int *choiceRe);
int main()
{
int x;
int num = 5;
for (int i = 0; i < 3; i++)
{
numGen_10(x, &x);
printf("val : %d \n", x);
}
printf("------------------------\n");
for (int i = 0; i < 4; i++)
{
numGen_4(4, x, &x);
printf("val2 : %d \n", x);
}
return 0;
}
void numGen_10(int xOry, int *xRey)
{
srand(time(NULL));
int r = rand() % 10 + 1;
xOry = r;
*xRey = xOry;
return;
}
void numGen_4(int num, int choice, int *choiceRe)
{
srand(time(NULL));
choice = rand() % num + 1;
*choiceRe = choice;
return;
}
The random number generator is completely deterministic; it will always output the same sequence of numbers for any given seed. srand() seeds the random number generator. So by calling srand() with the time immediately before each call to rand(), and since your loops will take less than a second to execute, you'll always get the same random number (or maybe two if the time happens to change in the middle).
Try calling srand() once before entering the loops.
Just for fun , add a delay of 1 second before each srand call when calling srand multiple times :
sleep(1);
/* or delay(1001); or usleep(500000);usleep(500000); based on availability */
srand(time(NULL));
Additional to what others said about solving problem of srand I would like to add a remark about how you use pointers, calling your functions with x and &x is pointless, you can just call either with pointer only or with variable only:
calling with pointer :
void numGen_10(int* xRey); // prototype
void numGen_10(int *xRey) // function's body
{
int r = rand() % 10 + 1;
*xRey = r;
return;
}
numGen_4(4, &x); // use from the main function
calling with variable :
int numGen_10(int xRey); // prototype
int numGen_10(int xRey) //function's body
{
int r = rand() % 10 + 1;
return r;
}
int y = numGen_4(4, x); // use from the main function
I need to generate 1000 random numbers inside a for loop.
my problem is that the random number generated is always the same. since im using time NULL to initiate the generator, why am i getting the same numbers? here is the code i used:
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 30000
int main(){
int i;
srand((long) time(NULL));
for(i = 0; i < 1000; i++){
int x = rand() % LIMIT;
printf("%d\n", x);
}
}
If you run the program multiple times during the same second, you will pass the same value to the generator as seed. You have to wait at least a second before trying it again.
This is because the time function returns the number of seconds since a specific time, and if called multiple times during the same second will return the same value.
your code is right, but you forgot to include the time.h library.
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // <--- now it works
#define LIMIT 30000
int main(){
int i;
srand((long) time(NULL));
for(i=0;i<1000;i++){
int x = rand() % LIMIT;
printf("%d",x);}