#28982 [Opn->Bgs]: rand()%4 is cyclical

From: Date: Wed, 14 Jul 2004 17:21:24 +0000
Subject: #28982 [Opn->Bgs]: rand()%4 is cyclical
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-62270@lists.php.net to get a copy of this message
ID: 28982 Updated by: moriyoshi@php.net Reported By: chsnick at yahoo dot com -Status: Open +Status: Bogus Bug Type: Math related Operating System: Windows XP PHP Version: 5.0.0RC3 New Comment: Thank you for taking the time to write to us, but this is not a bug. Please double-check the documentation available at http://www.php.net/manual/ and the instructions on how to report a bug at http://bugs.php.net/how-to-report.php See: http://www.eskimo.com/~scs/C-faq/q13.18.html The tip is of C language, but PHP calls the rand() library function to generate random values, so it applies to PHP as well. Use mt_rand() and you might get better results. Previous Comments: ------------------------------------------------------------------------ [2004-07-01 08:05:30] chsnick at yahoo dot com Description: ------------ rand()%4 is cyclical. It proceeds from 0 to 1 to 2 to 3 to 0 to 1, etc. Reproduce code: --------------- srand(5); for($i = 0; $i < 30; $i++) { $j = rand(); $k = $j%4; echo "$k:$j<br>\n"; } Actual result: -------------- 2:14426 3:6795 0:22376 1:6017 2:38 3:21607 0:532 1:10941 2:30898 3:20483 0:11136 1:13753 2:28158 3:26975 0:32684 1:29813 2:27658 3:15483 0:27288 1:25329 2:16086 3:9559 0:6212 1:15661 2:29282 3:16371 0:29872 1:32553 2:21166 3:26703 ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=28982&edit=1

« previous php.bugs (#62270) next »