generate random number in a range [l u] [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate a random number from within a range - C
I saw the following code from programming pearls
int randint(int l, int u)
{ return l + (RAND_MAX*rand() + rand()) % (u-l+1);
}
Can anyone help me explain it?
Can we just use
return l + rand() % (u-l+1);
Thanks,

The problem with using rand() % n to get a number between 0 and n-1 is that it has some bias when n is not an exact divisor of RAND_MAX. The higher the value of n, the stronger this bias becomes.
To illustrate why this happens, let's imagine that rand() would be implemented with a six-sided die. So RAND_MAX would be 5. We want to use this die to generate random numbers between 0 and 3, so we do this:
x = rand() % 4
What's the value of x for each of the six outcomes of rand?
0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
As you can see, the numbers 0 and 1 will be generated twice as often as the numbers 2 and 3.
When your use case doesn't permit bias, this is a better way to calculate a random number:
(int)((double)rand() / (double)RAND_MAX * (double)n)

yes that is ok, check that u>l and you can do only this:
return l + (RAND_MAX*rand()) % (u-l+1);
explaination:
if we would like to generate in union distribution a random integer number in [0,N] when N>0 we would use:
return (RAND_MAX*rand()) % (N+1);
since the range is shitted with a constant value l in your case we just have to add it to the final result.
python model:
>>> import random
>>> import sys
>>> for i in xrange(20):
int(random.random()*sys.maxint%4)
0
1
2
3
1
1
2
2
3
0
3
3
0
2
3
3
1
2
2
3

Related

Round division of unsigned integers with no overflow

I'm looking for an overflow-safe method to perform round division of unsigned integers.
I have this:
uint roundDiv(uint n, uint d)
{
return (n + d / 2) / d;
}
But unfortunately, the expression n + d / 2 may overflow.
I think that I will have to check whether or not n % d is smaller than d / 2.
But d / 2 itself may truncate (when d is odd).
So I figured I should check whether or not n % d * 2 is smaller than d.
Or even without a logical condition, rely on the fact that n % d * 2 / d is either 0 or 1:
uint roundDiv(uint n, uint d)
{
return n / d + n % d * 2 / d;
}
This works well, however once again, n % d * 2 may overflow.
Is there any custom way to achieve round integer division which is overflow-safe?
Update
I have come up with this:
uint roundDiv(uint n, uint d)
{
if (n % d < (d + d % 2) / 2)
return n / d;
return n / d + 1;
}
Still, the expression d + d % 2 may overflow.
return n/d + (d-d/2 <= n%d);
The way to avoid overflow at any stage is, as OP stated, to compare the remainder with half the divisor, but the result isn't quite as obvious as it first seems. Here are some examples, with the assumption that 0.5 would round up. First with an odd divisor:
Numerator Divisor Required Quotient Remainder Half divisor Quot < Req?
3 3 1 1 0 1 no
4 3 1 1 1 1 no
5 3 2 1 2 1 yes
6 3 2 2 0 1 no
Above, the only increment needed is when d / 2 < remainder. Now with an even divisor:
Numerator Divisor Required Quotient Remainder Half divisor Quot < Req?
4 4 1 1 0 2 no
5 4 1 1 1 2 no
6 4 2 1 2 2 yes
7 4 2 1 3 2 yes
8 4 2 2 0 2 no
But here, the increment is needed when d / 2 <= remainder.
Summary:
You need a different condition depending on odd or even divisor.

Generate random even number in range [m, n]

I was looking for C code to generate a set of random even number in range [start, end]. I tried,
int random = ((start + rand() % (end - start) / 2)) * 2;
This won't work, for example if the range is [0, 4], both 0 & 4 included
int random = (0 + rand() % (4 - 0) / 2) * 2
=> (rand() % 2) * 2
=> 0, 2, ... (never includes 4) but expectation = 0, 2, 4 ...
On the other hands if I use,
int random = ((start + rand() % (end - start) / 2) + 1) * 2;
This won't work, for example,
int random = (0 + (rand() % (4 - 0) / 2) + 1) * 2
=> ((rand() % 4 / 2) + 1) * 2
=> 2, 4, ... (never includes 0) but expectation = 0, 2, 4 ...
Any clue? how to get rid of this problem?
You complicated it too much. Since you're using rand() and the modulo operator, I'm assuming that you will not be using this for cryptographic or security purposes, but as a simple even number generator.
The formula I have found for generating a random even number in the range of [0, 2n] is to use
s = (rand() % (n + 1)) * 2
An example code:
#include <stdio.h>
int main() {
int i, s;
for(i = 0; i < 100; i++) {
s = (rand() % 3) * 2;
printf("%d ", s);
}
}
And it gave me the following output:
2 2 0 2 4 2 2 0 0 2 4 2 4 2 4 2 0 0 2 2 4 4 0 0 4 4 4 2 2 2 4 0 0 0 4 0 2 2 2 2 0 0 0 4 4 2 4 4 4 0 4 2 2 4 4 0 4 4 2 2 0 0 4 0 4 4 2 0 2 4 0 0 0 0 4 0 4 4 0 4 2 0 0 4 4 0 0 4 4 2 0 0 4 0 2 2 2 0 0 4 0 2 4 2
Best regards!
rand() % x will generate a number in the range [0,x) so if you want the range [0,x] then use rand() % (x+1)
Common notation for ranges is to use [] for inclusive and () for exclusive, so [a,b) would be a range such that a is included but not b.
So in your case, just use (rand() % 3)*2 to get random numbers among {0,2,4}
If you want even numbers in the range [m,n], then use ((m/2) + rand() % ((n-m+2)/2))*2
I do not trust in the mod operator for random numbers. I prefer
start + ((1 + stop - start) * rand())
/ (1 + RAND_MAX)
which only relies on the distribution of rand() in the interval
[0, .. , RAND_MAX] and not on any distribution of rand()%n in the
interval [0, .. , n-1].
Note: If you use this expression you should add appropriate casts to avoid multiplication overflow.
Note also
ISO/IEC 9899:201x (p.346):
There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient for their needs.
Just and-out the low bit, which makes it even:
n= (rand()%N)&(-2);
and to use a start/stop (a range), the values can be offset:
int n, start= 5, stop= 20+1;
n= ((rand()%(stop-start))+start)&(-2);
The latter calculation generates a random number between 0 and RAND_MAX (this value is library-dependent, but is guaranteed to be at least 32767).
If the stop value must be included in the range of generated numbers, then add 1 to the stop value.
It takes that value modulo the stop value plus the start value, and then adds the start value. The value is now within the range of [start, stop]. As only even numbers are required, the low bit is anded-out because even numbers start at 2.
The anding-out is performed by generating a mask of all 1's, except the lowest bit. As -1 is all 1's (0xFFF...FFFFF), -2 is all 1's except this low bit (0xFFF...FFFFE). Next the bitwise AND operation (&) is perfomed with this mask and the number is now in the range [start,stop]. QED.

C rand() dice issue

I'm new to C and I'm reading a book about it. I just came across the rand() function. The book states that using rand() returns a random number from 0 to 32767. It also states that you can narrow the random numbers by using % (modulus operator) to do so.
Here is an example: the following expression puts a random number from 1 to 6 in the variable dice
dice = (rand() % 5) + 1;
I'm unable to get a remainder of 5 as any number from 0 to 33767 % 5 is equal to 0 to 4, but never 5.
Shouldn't it be % 6 in the above statement instead?
For example, if I choose randomly a number between 0 and 32767, let's say 75, then:
75 % 5 == 0
76 % 5 == 1
77 % 5 == 2
78 % 5 == 3
79 % 5 == 4
80 % 5 == 0
Etc.
So regardless of the random number between 0 and 32767, the remainder will never be 5, so it will not be possible to get a 6 number for the dice (as per the above statement).
Not sure if you will understand what I mean but your help would be much appreciated.
dice = (rand() % 5) + 1;
This will generate a random number between 1 to 5, inclusive, as you have analyzed. The % 5 in the book is probably just a typo. To get 1 to 6 it needs to be % 6.
First you will have to understand how modulo (%) works. If you have say 10 and divide it by 5 you get 2 with a remainder of 0, hence the 10 % 5. The possible range of remainders you would get when you mod(modulo) 5 is 0 - 4. Remember that the possible remainders would can get when you divide by x if from 0 to x-1. So in your case with the dice program you need numbers from the range of 1 to 6 (the faces of a die) hence you would mod 6 and add 1 to this number for give the necessary shift. (rand() % 6) + 1

What is the total number of nested loop execution?

Q1 - At the following double-nested loop what will be the final value in m if loop does for n.
Of course it is not desired to do loop and see what the m is! Since n can be very large!
m = 0
for i = 1 to n-2
for j = i+1,n-1
for k = j+1,n
m += 1
Q2 - How did you find the answer? I mean what was the algorithm/technique that you used to solve the problem?
Q3 - What are your recommendation to solve similar problems?
Here is the answer that I was looking for:
Answer:
def ntn(n,k):
"""returns the number of iterations for k nested dependent loops(n)"""
return long(np.prod(n-np.arange(k,dtype=float)) /
np.prod(np.arange(k,dtype=float)+1))
example:
>>> ntn(1000,4)
41417124750L
>>> ntn(1e20,3)
166666666666666650797607483335462097315368077619447843520512L
Q3: Find a pattern to the question.
Q2: Assuming n:=10
Notice that i will loop from 1 to 8
Therefore, j will loop from
2 to 9
3 to 9
...
9 to 9
Therefore, k will loop from
loops value index
3 to 10, 4 to 10, 5 to 10, ..., 10 to 10 8 + 7 + 6 + ... + 1 8
4 to 10, 5 to 10, ..., 10 to 10 7 + 6 + ... + 1 7
5 to 10, ..., 10 to 10 6 + ... + 1 6
... ... ... ...
10 to 10 1 1
Notice the pattern here: if we start the index from the bottom number (1), to get the mth number in the sequence, you simply sum 1 through m.
Q1: You figure this one out on your own. Hint: it's a summation of summations...
Answer:
Combination formula is as follows:
can be used for this purpose.
In Python there is comb() function within scipy package which can be used too.
However the following solution is much more flexible and faster and the resulting digits are much longer.
import numpy as np
def ntn(n,k):
"""returns the number of iterations for k nested dependent loops(n)"""
return long(np.prod(n-np.arange(k,dtype=float)) /
np.prod(np.arange(k,dtype=float)+1))
Examples:
>>> ntn(1000,4)
41417124750L
>>> ntn(1e20,3)
166666666666666650797607483335462097315368077619447843520512L

How does modulus of a smaller dividend and larger divisor work?

7 % 3 = 1 (remainder 1)
how does
3 % 7 (remainder ?)
work?
remainder of 3/7 is 3..since it went 0 times with 3 remainder so 3%7 = 3
7 goes into 3? zero times with 3 left over.
quotient is zero. Remainder (modulus) is 3.
Conceptually, I think of it this way. By definition, your dividend must be equal to (quotient * divisor) + modulus
Or, solving for modulus: modulus = dividend - (quotient * divisor)
Whenever the dividend is less than the divisor, the quotient is always zero which results in the modulus simply being equal to the dividend.
To illustrate with OP's values:
modulus of 3 and 7 = 3 - (0 * 7) = 3
To illustrate with other values:
1 % 3:
1 - (0 * 3) = 1
2 % 3:
2 - (0 * 3) = 2
The same way. The quotient is 0 (3 / 7 with fractional part discarded). The remainder then satisfies:
(a / b) * b + (a % b) = a
(3 / 7) * 7 + (3 % 7) = 3
0 * 7 + (3 % 7) = 3
(3 % 7) = 3
This is defined in C99 ยง6.5.5, Multiplicative operators.
7 divided by 3 is 2 with a remainder of 1
3 divided by 7 is 0 with a remainder of 3
As long as they're both positive, the remainder will be equal to the dividend. If one or both is negative, then you get reminded that % is really the remainder operator, not the modulus operator. A modulus will always be positive, but a remainder can be negative.
(7 * 0) + 3 = 3; therefore, the remainder is 3.
a % q = r means there is a x so that q * x + r = a.
So, 7 % 3 = 1 because 3 * 2 + 1 = 7,
and 3 % 7 = 3 because 7 * 0 + 3 = 3
It seems you forgot to mention the surprising case, if the divident is smaller and negative:
-3 % 7
result: 4
For my brain to understand this kind of question, I'm always converting it to a real world object, for example if I convert your question 3 % 7. I'm going to represent the "3" as a 3-inch wide metal hole, then the "7" as a 7 inch metal screw. Can you insert the 7 inch metal screw to a 3 inch wide metal hole? Of course not, therefore the answer should be the 3-inch metal hole, it doesn't matter even let say you have a 1000 or a million inch wide screw, it is still 3, because how many times can you insert the 1000 or a million inch wide screw to a 3 inch wide metal hole? Zero times, right?
The most simple and effective catch to remember would be:
Whenever dividend is less than the divisor, modulus is just that dividend.
Let's formulate this:
if x < y, then x % y = x

Resources