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 ?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
// 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.
回答2:
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
回答3:
Check out the answers to this question.