Generating random number between [-1, 1] in C?

后端 未结 7 872
北恋
北恋 2020-12-08 21:57

I have seen many questions on SO about this particular subject but none of them has any answer for me, so I thought of asking this question.

I wanted to generate a r

7条回答
  •  醉话见心
    2020-12-08 23:00

    While the accepted answer is fine in many cases, it will leave out "every other number", because it is expanding a range of already discrete values by 2 to cover the [-1, 1] interval. In a similar way if you had a random number generator which could generate an integer from [0, 10] and you wanted to generate [0, 20], simply multiplying by 2 will span the range, but not be able to cover the range (it would leave out all the odd numbers).

    It probably has sufficiently fine grain for your needs, but does have this drawback, which could be statistically significant (and detrimental) in many applications - particularly monte carlo simulations and systems which have sensitive dependence on initial conditions.

    A method which is able to generate any representable floating point number from -1 to 1 inclusive should rely on generating a sequence a1.a2 a3 a4 a5 ... up to the limit of your floating point precision which is the only way to be able to generate any possible float in the range. (i.e. following the definition of the real numbers)

提交回复
热议问题