Understanding “randomness”

前端 未结 28 2507
轻奢々
轻奢々 2020-11-22 15:28

I can\'t get my head around this, which is more random?

rand()

OR:

rand() * rand()

I´m f

28条回答
  •  旧巷少年郎
    2020-11-22 16:01

    Actually, when you think about it rand() * rand() is less random than rand(). Here's why.

    Essentially, there are the same number of odd numbers as even numbers. And saying that 0.04325 is odd, and like 0.388 is even, and 0.4 is even, and 0.15 is odd,

    That means that rand() has a equal chance of being an even or odd decimal.

    On the other hand, rand() * rand() has it's odds stacked a bit differently. Lets say:

    double a = rand();
    double b = rand();
    double c = a * b;
    

    a and b both have a 50% precent chance of being even or odd. Knowing that

    • even * even = even
    • even * odd = even
    • odd * odd = odd
    • odd * even = even

    means that there a 75% chance that c is even, while only a 25% chance it's odd, making the value of rand() * rand() more predictable than rand(), therefore less random.

提交回复
热议问题