Error with rand() function: same numbers into a for loop - c

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.

Related

C modulo operator behaving unusually with randomly generated integer in my code

In the following code of mine, the modulo operator is used on two randomly generated numbers but the output is often incorrect. Why would that happen?
Here's an example of unexpected output:
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void delay(int number_of_seconds)
{
// Converting time into milli_seconds
int milli_seconds = 1000 * number_of_seconds;
// Storing start time
clock_t start_time = clock();
// looping till required time is not achieved
while (clock() < start_time + milli_seconds)
;
}
void ran_dom(){ //this function generates a random number and prints its remainder
srand(time(0));
int x = (int) rand();
int y = (int) rand();
printf("x: %d\n", x);
printf("y: %d\n", y);
int mod_x = (x % 40); //modulo operator with value: 40
int mod_y = (y % 20); //modulo operator with value: 20
printf("x mod 40: %d\n", mod_x);
printf("y mod 20: %d\n", mod_y);
}
void ResetScreenPosition(){ //resets screen position (in windows OS)
COORD Position;
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
void main(){
while(1){
ResetScreenPosition();
ran_dom();
delay(2);
}
}
Thanks for taking a look!
6327 % 40 is 7. If the screen has 23 in the position of the 7 from a previous print, printing "x mod 40: 7" will appear to have printed "x mod 40: 73".
Try something along the lines of one of these alternatives:
printf("x mod 40: %02d \n", mod_x);
printf("[x mod 40: %d]\n", mod_x);
To my knowledge there is no standard way of clearing the screen in c.
The error in your output came from overwriting the screen without clearing it.
Also there is a sleep(int seconds) function in unistd.h. Using it is probably a better idea than looping.
Calling srand() once is enough. You don't need to set your random seed each call.
This would probably be my implementation:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
void clear_screen() {
#ifdef WINDOWS
system("cls");
#else
/* Assume POSIX */
system ("clear");
#endif
}
void print_random() {
int x, y, mod_x, mod_y;
x = rand();
y = rand();
printf("x: %d\n", x);
printf("y: %d\n", y);
mod_x = (x % 40);
mod_y = (y % 20);
printf("x mod 40: %d\n", mod_x);
printf("y mod 20: %d\n", mod_y);
}
int main() {
srand(time(NULL));
while(1) {
clear_screen();
print_random();
sleep(2);
}
return 0;
}
Since I don't have a Windows machine on hand right now I could only test this code on my Ubuntu. Should work though.
I just discovered that placing this piece of code after calling delay() from the main function works too:
system("cls"); // refreshes screen? works!

How can I use two random numbers generated in a function as matrix coordinates?

I came up with this function to generate two random numbers, r and c, so that I can use them in as coordinates in matrix board[r][c]. Is this even possible?
int coordAleatoria()
{
srand((unsigned int)time(0));
int r=rand()%9;
int c=rand()%9;
while(r==c)
{
c=rand()%9;
}
printf("%d %d", r, c);
return r;
return c;
}
This is for a chess-like game. The PC is supposed to generate random moves. This function does generate coordinates, I'm just not sure how to make my program treat them as coordinates.
I hope I can get r and c in board[r][c] to be the values generated in coordAleatoria().
You cannot return more than one time. So you can combine the coordinates using structure as Jabberwocky suggested in the comment. If you are still finding it difficult than here is the implementation.
#include<stdio.h>
#include<stdlib.h>//for rand()
#include<time.h>//for time()
struct Pair
{
int row,col;
};
struct Pair coordAleatoria()
{
int r=rand()%9;
int c=rand()%9;
while(r==c)
{
c=rand()%9;
}
printf("Inside function: row=%d and col=%d\n",r,c);
//Create a pair
struct Pair p;
//Assign values
p.row=r,p.col=c;
//return it
return p;
}
int main()
{
srand((unsigned int)time(0));
//Get the returned value as a Pair
struct Pair p=coordAleatoria();
//Collect the row and column values
int r=p.row;
int c=p.col;
//Now you can use them here
printf("Outside function: row=%d and col=%d\n",r,c);
}
rand()%9 generates 9 different values. With while(r==c), looks like code is looking for 9*(9-1) or 72 different pairs. For a speedier approach, call rand() once.
Code could return a single int and later divine/mod by 9 to recover the row/column.
srand((unsigned int)time(0)); should not be repeated called in coordAleatoria(). Call it once, perhaps in main().
int coordAleatoria(void) {
int rc = rand()%72;
int r = rc/9;
int c = rc%9;
if (r==c) r++;
return (r*9) + c;
}
Rather than calling rand() twice (after properly seeding the random number generator with a call to srand()), you can simply call rand() once and take the first two digits as your coordinates, e.g.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int x, y;
} pair_t;
void rand_coords (pair_t *coords)
{
int n = rand();
coords->x = n % 10;
n /= 10;
coords->y = n % 10;
}
int main (void) {
pair_t coords = { .x = 0 };
srand (time (NULL)); /* seed random number generator */
rand_coords (&coords);
printf ("coords.x : %d\ncoords.y : %d\n", coords.x, coords.y);
return 0;
}
(or take the modulo of whatever your actual coordinate range is)
Example Use/Output
$ ./bin/coords_rand
coords.x : 9
coords.y : 8
$ ./bin/coords_rand
coords.x : 1
coords.y : 1
$ ./bin/coords_rand
coords.x : 5
coords.y : 7
$ ./bin/coords_rand
coords.x : 8
coords.y : 0

How do you retrieve a number from a function to use it in another function?

(C code) Each die has its own function, and I want a function that will sum the outcome of each die. But how do I retrieve the values from the first and second functions and put them into the third to sum them? See below
int roll_die1(void)
{
int random_int;
srand((unsigned int)time(NULL));
random_int = rand() % (6) + 1;
printf("The outcome of your first Roll is: %d.\n", random_int);
return random_int;
}
int roll_die2(void)
{
int random_int2;
srand((unsigned int)time(NULL));
random_int2 = rand() % (6) + 1;
printf("The outcome of your second Roll is: %d.\n", random_int2);
return random_int2;
}
int calculate_sum_dice(int die1_value, int die2_value)
{
int sum = die1_value + die2_value;
return sum;
}
Now I can't just call the first two functions into the 3rd function, because it would repeat all the steps in those functions, so how do I do it?
Edit: In my main.c, to get the sum I did
roll1 = roll_die1();
roll2 = roll_die2();
sum = calculate_sum_dice(roll1, roll2);
Just allow calculate_sum_dice() to retrieve both results from roll_die1() and roll_die2() and return the sum. Their is no need to include any function parameters for calculate_sum_dice(). You can also just call srand() once in main(), as it just sets a seed for rand(), so it would be pointless to call it more than once. Have a look at srand(): why call it just once?, as pointed out by #Jonathan Leffler in the comments.
Here is what your code should look like:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int roll_die1(void) {
int random_int;
random_int = rand() % (6) + 1;
printf("The outcome of your first Roll is: %d.\n", random_int);
return random_int;
}
int roll_die2(void) {
int random_int2;
random_int2 = rand() % (6) + 1;
printf("The outcome of your second Roll is: %d.\n", random_int2);
return random_int2;
}
int calculate_sum_dice(void) {
int sum = roll_die1() + roll_die2();
return sum;
}
int main(void) {
srand((unsigned int)time(NULL));
int sum = calculate_sum_dice();
printf("Dice sum = %d\n", sum);
return 0;
}

Generating a random, uniformly distributed real number in C [duplicate]

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

Random number generator C

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

Resources