php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #28982 rand()%4 is cyclical
Submitted: 2004-07-01 08:05 UTC Modified: 2004-07-14 19:21 UTC
From: chsnick at yahoo dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.0.0RC3 OS: Windows XP
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: chsnick at yahoo dot com
New email:
PHP Version: OS:

 

 [2004-07-01 08:05 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-07-14 19:21 UTC] moriyoshi@php.net
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.

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Jul 14 17:01:28 2024 UTC