Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP rand() ...get true 50/50 results?

Tags:

php

I want to run a function that has 2 different outcomes, but I want each outcome to be truly 50%. I am assuming rand(0,1) is the way to go, but I am curious if that could possibly favor one over the other. What is the best way to get a 50/50 outcome?

Thanks.

EDIT: thanks guys I don't want it to be random though, I want the outcome to be 101010101 not 111001101. Maybe I should just update a data-base with the last value output and then return the opposite?

EDIT2: OK I am sorry my last edit was misleading. I am only calling the function once per user and assigning that value as a cookie to the user. I want each visiting user to receive a 1 or a 0 in the order 1010101.

like image 856
JD Isaacks Avatar asked Mar 18 '09 14:03

JD Isaacks


1 Answers

in PHP mt_rand() is a better random number generator

mt_rand(0,1);

Is enough and should generate a pretty good 50/50 value.

Quote about mt_rand:

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this.

It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

Bill had a good link regarding a visual example. I do not know what PHP the user had there for PHP but since he included the code i have hosted it on my server (Linux with PHP 5.1.6)

  • rand() Visual Example
  • mt_rand() Visual Example
like image 110
Ólafur Waage Avatar answered Oct 12 '22 01:10

Ólafur Waage