Why does C++ rand() seem to generate only numbers of the same order of magnitude?

前端 未结 9 2079
孤独总比滥情好
孤独总比滥情好 2021-01-30 01:14

In a small application written in C/C++, I am facing a problem with the rand function and maybe the seed :

I want to produce a sequence of random numbers th

9条回答
  •  面向向阳花
    2021-01-30 02:01

    @C4stor made a great point. But, for a more general case and easier to understand for human (base 10): for the range from 1 to 10^n, ~90% of the numbers are from 10^(n-1) to 10^n, therefore, ~99% of the numbers go from 10^(n-2) to 10^n. Keep adding as many decimals as you want.

    Funny mathematics, if you keep doing this for n, you can see that from 1 to 10^n, 99.9999...% = 100% of the numbers are from 10^0 to 10^n with this method.

    Now about code, if you want a random number with random orders of magnitude, from 0 to 10^n, you could do:

    1. Generate a small random number from 0 to n

    2. If you know the range that n has, generate a big random number of order 10^k where k > max{n}.

    3. Cut the longer random number to get the n digits of this big random number.

提交回复
热议问题