Hi It is possible to generate random number within a range (-x,x) using rand()?? If not, how can I generate random number withing that range ?
Asked
Active
Viewed 2,818 times
3 Answers
5
// return a random number between 0 and limit inclusive.
int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
// Return a random number between lower and upper inclusive.
int rand_lim(int lower, int upper) {
int range = abs(upper-lower);
return rand_lim(range) + lower;
}
As usual, all the others I've seen in this thread can/will produce at least slightly skewed results.

Jerry Coffin
- 476,176
- 80
- 629
- 1,111
-
Alas, this might return skewed results as well, although it will probably not be by very much. The first `RAND_MAX%(limit+1)` numbers will be favored if `RAND_MAX%(limit+1) < limit`. – Jørgen Fogh Feb 26 '11 at 19:38
-
1To chip in on the *skewed* bit. Let's suppose that `rand()` generates an integer in `[0..15]` with perfect uniformity, and say we want to generate a random integer between in `[-3..3]`. The usual operation consists in *folding* `[0..15]` onto `[-3..3]`: `[0..6]` and `[7..13]` map to `[-3..3]` perfectly (ie, when `rand()` returns `1` or `8`, we output `-2`)... but what happens when `rand()` returns `14` or `15` ? If we map them to `-3` and `-2` respectively, then we have a *skewed* distribution, since it's slightly more likely to get `-3` or `-2` than any other number. – Matthieu M. Feb 26 '11 at 19:42
1
I am just a simple Basic programmer, but I feel like I am missing the point. The answer seems simple. Please pardon the VB code
Dim prng As New Random
Const numEach As Integer = 100000
Const x As Integer = 3 'generate random number within a range (-x,x) inclusive
Dim lngth As Integer = Math.Abs(-x - x) + 1
Dim foo(lngth - 1) As Integer 'accumualte hits here
For z As Integer = 1 To (numEach * lngth)
Dim n As Integer = prng.Next(lngth) 'generate number in inclusive range
foo(n) += 1 'count it
'n = x - n 'actual n
Next
Debug.WriteLine("Results")
For z As Integer = 0 To foo.Length - 1
Debug.WriteLine((z - x).ToString & " " & foo(z).ToString & " " & (foo(z) / numEach).ToString("n3"))
Next
Debug.WriteLine("")
Typical results
Results
-3 99481 0.995
-2 100214 1.002
-1 100013 1.000
0 100361 1.004
1 99949 0.999
2 99755 0.998
3 100227 1.002
Results
-3 100153 1.002
-2 99917 0.999
-1 99487 0.995
0 100383 1.004
1 100177 1.002
2 99808 0.998
3 100075 1.001

dbasnett
- 11,334
- 2
- 25
- 33