How to generate random number within range (-x,x)

2019-01-15 17:26发布

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 ?

标签: c++ random
3条回答
我只想做你的唯一
2楼-- · 2019-01-15 18:06

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楼-- · 2019-01-15 18:10

Check out the answers to this question.

查看更多
女痞
4楼-- · 2019-01-15 18:12
// 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.

查看更多
登录 后发表回答