Reputation: 11
Im trying to generate random numbers between 5 and 40000 with using rand() function.And add them to 3x3 matris. I have tried multiply rand with rand and mod 39996 is that correct solution you think ?
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
srand(time(0));
int **matris;
matris=(int **)calloc(3,sizeof(int)); // ilk pointerla 3 kutuya boldum yani 3 satir
for(int i=0;i<3;i++){
matris[i]=calloc(3,sizeof(int)); // buradada 3 kutunun herbirinin icini 3e boldum
}
for(int i=0;i<3;i++){ // i= matrisin satirini j= matrisin sutununu temsil ediyor
for(int j=0;j<3;j++){
matris[i][j]= 5 + ((rand()*rand())%39996); // burada rand() fonksiyonunun karesini alip isleme devam ettim. 5 ile 40000 arasi sayilar olusturuyor.
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
printf("%d\t",matris[i][j]);
}
printf("\n");
}
return 0;
}
Upvotes: 0
Views: 151
Reputation: 153447
When RAND_MAX
is large, the below is sufficient, although it has a bias.
matris[i][j] = 5 + (rand() % 39996);
As RAND_MAX
may only be 32767 (as apperntly in OP's case) , we need more random bits.
if (RAND_MAX == 32767) {
long r = rand();
r *= (RAND_MAX + 1L);
r += rand();
matris[i][j] = 5 + (r % 39996);
} else {
matris[i][j] = 5 + (rand() % 39996);
}
rand()*rand()
does not form a uniform distribution. In this case we want (RAND_MAX+1)*(RAND_MAX+1)
different values.
The range of random numbers generated needs to be at least [0...39996).
Upvotes: 2
Reputation: 108978
If you're not worried about bias (*)
randomvalue = rand() % 39996 + 5;
*some values will have a higher probability of being chosen than others*
RAND_MAX
is 32767
Hmmm...
call rand()
twice and use one single bit from one of the values
// return unbiased random between 5 and 40000
// assuming RAND_MAX == 32767
int unbiased(void) {
int value;
do {
value = rand(); // 0 to 32767
value = value * 2; // even value from 0 to 65534
if (rand() & 0x800) value = value + 1; // 0 to 65535
} while (value > 39995); // ignore biased results
return value + 5;
}
Upvotes: 0
Reputation: 1
int random(int min, int max) {
return (rand() % (max - min + 1)) + min;
}
Upvotes: 0
Reputation: 134
https://www.geeksforgeeks.org/generating-random-number-range-c/
As C does not have an inbuilt function for generating a number in the range, but it does have rand function which generate a random number from 0 to RAND_MAX. With the help of rand()
a number in range can be generated as num = (rand() % (upper – lower + 1)) + lower
Upvotes: 1