Tuesday, May 20, 2008

PHP rand(0,1) on Windows < OpenSSL rand() on Debian

512x512 image made using `if rand(0,1)` on PHP/Windows

(Please excuse the inflammatory title.)

Bo Allen recently made a post regarding the difference between true random and pseudorandom numbers, using 512x512 bitmaps as illustration.

Some might doubt his result on Windows, as the image seems to be too predictable. Initially, I passed it off as PHP using the default Windows pseudorandom number generator, which is a Linear Congruential Generator.

The default windows rand() function is implemented as follows (coefficients from this site, many others have them also):

unsigned long randState = 0;

//Get random number
unsigned long rand(void) {
randState = randState * 214013 + 2531011L;
return (randState >> 16) & 0x7fff;
}

//Seed RNG
void srand(unsigned long seed) {
randState = seed;
}

Here is Bo Allen's code:
// Requires the GD Library
header ("Content-type: image/png");
$im = @imagecreatetruecolor(512, 512)
or die("Cannot Initialize new GD image stream");
$white = imagecolorallocate($im, 255, 255, 255);
for($y=0;$y<512;$y++){
for($x=0;$x<512;$x++){
if(rand(0,1)===1){
imagesetpixel($im, $x, $y, $white);
}
}
$x=0;
}
imagepng($im);
imagedestroy($im);


Let's have a look at how PHP does rand(0,1). All code is from the php-5.2.6 source release.

//ext/standard/rand.c:296-315
/* {{{ proto int rand([int min, int max])
Returns a random number */
PHP_FUNCTION(rand)
{
long min;
long max;
long number;
int argc = ZEND_NUM_ARGS();

if (argc != 0 &&
zend_parse_parameters(argc TSRMLS_CC, "ll", &min, &max) == FAILURE)
return;

number = php_rand(TSRMLS_C);
if (argc == 2) {
RAND_RANGE(number, min, max, PHP_RAND_MAX);
}

RETURN_LONG(number);
}
/* }}} */


A bit of digging reveals that php_rand is just a wrapper to the system's random() function. Okay, so what exactly is RAND_RANGE?

//ext/standard/php_rand.h:43-44
#define RAND_RANGE(__n, __min, __max, __tmax) \
(__n) = (__min) + (long) ((double) ( (double) (__max) - (__min) + 1.0) \
* ((__n) / ((__tmax) + 1.0)))

Wow, that is some ugly code.

Python's default random generator uses Mersenne Twister, which is an excellent choice for any application outside of cryptography. Here's code that replicates Bo's experiment, including a re-implementation of php's broken rand() function.


import PIL.Image, random, time

class MsftRand(random.Random):
'''This is equivalent to rand() and srand() on the Windows platform'''
state = 0
def __init__(self): # constructor method
self.state = int(time.time()) # seconds since the epoch
def seed(self,s):
self.state = s
def setstate(self,s):
self.state = s
def getstate(self):
return self.state
def random(self): # returns a float [0,1)
self.state = (self.state * 214013 + 2531011) % 2**32
return float((self.state >> 16) & 0x7fff) / 2**15

class bogoRand(MsftRand):
'''This replicates how PHP does randint()'''
def randint(self, a, b):
self.state = (self.state * 214013 + 2531011) % 2**32
return a + int(float((float(b-a+1)*((self.state&0x7fff)/((1<<15)+1.0)))))

image = PIL.Image.new("1",(512,512)) # Creates a 512x512 bitmap

# creates a list of different RNG objects and names
rand_mapping = [ (MsftRand(), "Microsoft"),
(random.Random(), "Mersenne"),
(bogoRand(), "bogoRand") ]

for rnd, name in rand_mapping:
for y in xrange(512):
for x in xrange(512):
image.putpixel((x,y), rnd.randint(0,1))
image.save("random_"+name+".png")

This will create three images when you run it--random_Mersenne.png, which uses Python's default random generator and randint() implementations, random_Microsoft.png, which uses the Windows LCG and Python's randint() implementation, and random_bogoRand.png, which uses the Windows LCG and PHP's randint() implementation.

Here's what random_bogoRand.png looks like:

This doesn't look exactly like Bo's image, as I probably didn't exactly replicate all the quirks of PHP's RAND_RANGE macro. I could be using the wrong LCG as well.

The other two images have no patterns obvious to the eye. How does Python do randint()?

from Lib/rand.py:

def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
def randrange(self, start, stop):
#I'm paraphrasing here, it does checks to make sure the arguments
# are integers and other sanity stuff
return start + int(self.random() * (stop - start))

It's not that PRNGs are visibly flawed, it's that PHP has a terrible method of generating a random range.

Labels: , , ,

251 Comments:

«Oldest ‹Older 201 – 251 of 251
Blogger Prakash said...

Awesome Post!!! Thanks for sharing this great post with us.
JAVA Training in Chennai
Java training institute in chennai
JAVA J2EE Training in Chennai
J2EE Training in Chennai
java training in vadapalani
java training in porur
Python Training in Chennai
Hadoop Training in Chennai
Big data training in chennai
Selenium Training in Chennai

September 24, 2019 at 4:34 AM  
Blogger Techy said...

For Data Science training in Bangalore, Visit:
Data Science training in Bangalore

September 24, 2019 at 5:27 AM  
Blogger daxcooke said...

Dax Cooke

September 26, 2019 at 2:08 AM  
Blogger rinjuesther said...

Nice Blog, Very Informative Content,waiting for next update...
clinical sas training in chennai
clinical sas training
clinical sas Training in Anna Nagar
clinical sas Training in T Nagar
clinical sas Training in OMR
SAS Training in Chennai
Spring Training in Chennai
LoadRunner Training in Chennai
QTP Training in Chennai
javascript training in chennai

September 26, 2019 at 4:23 AM  
Blogger Unknown said...

data sgp
data sydney
datahk
syair sydney
syairsgp
datasgp
paito warna
http://warungsgp.com/
live hk 6d
live sydney

September 26, 2019 at 4:39 PM  
Blogger jose said...

Really nice post. Thank you for sharing amazing information.
Java Training in Credo Systemz/Java Training in Chennai Credo Systemz/Java Training in Chennai/Java Training in Chennai with Placements/Java Training in Velachery/Java Training in OMR/Java Training Institute in Chennai/Java Training Center in Chennai/Java Training in Chennai fees/Best Java Training in Chennai/Best Java Training in Chennai with Placements/Best Java Training Institute in Chennai/Best Java Training Institute near me/Best Java Training in Velachery/Best Java Training in OMR/Best Java Training in India/Best Online Java Training in India/Best Java Training with Placement in Chennai

September 26, 2019 at 10:24 PM  
Blogger Raj said...

Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Course In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai

September 26, 2019 at 11:34 PM  
Blogger Raj said...

Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

September 26, 2019 at 11:34 PM  
Blogger Raj said...

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

September 26, 2019 at 11:34 PM  
Blogger KIT said...

A very inspiring blog your article is so convincing that I never stop myself to say something about it.

September 27, 2019 at 3:31 AM  
Blogger Riya Raj said...

Phenomenal Blog!!! thanks for your post and awaiting for your new updates...
Digital Marketing Course in Chennai
Digital Marketing Training in Chennai
best digital marketing course in chennai
Digital Marketing Course
Digital marketing course in Thiruvanmiyur
Digital marketing course in Velachery
Python Training in Chennai
Software testing training in chennai
Python Training in Chennai
JAVA Training in Chennai

September 27, 2019 at 4:35 AM  
Blogger Tyler Worgan said...

I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers
tree service near me in lantana

September 27, 2019 at 6:09 AM  
Blogger Chris Hemsworth said...

The article is so informative. This is more helpful for our
selenium training in chennai
selenium online courses best selenium online training
selenium testing training
selenium classes
Thanks for sharing.

September 27, 2019 at 10:18 PM  
Blogger Tyler Worgan said...

Very nice bro, thanks for sharing this with us. Keep up the good work and Thank you for sharing information
bathroom remodel houston tx

September 28, 2019 at 5:32 AM  
Blogger David Bryns said...

Thanks for an amazing blog.
Click Here

September 28, 2019 at 6:25 AM  
Blogger Tyler Worgan said...

I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers.
tree service royal palm beach

September 28, 2019 at 7:48 AM  
Blogger The India said...

Delhi Mathura Vrindavan Tour by Bus
Agra Mathura Tour Package by Bus
Delhi to Agra tour by Volvo bus
Online Bus Ticket Booking for Agra
Same Day Agra Tour
Same Day Agra Tour by Bus

September 29, 2019 at 10:34 PM  
Blogger neomacooper said...

You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!!
residential tree services tampa

October 1, 2019 at 4:47 AM  
Blogger Lee Davis said...

Very nice bro, thanks for sharing this with us. Keep up the good work and Thank you for sharing information vinyl fence nashville

October 1, 2019 at 5:05 AM  
Blogger shivam said...


Top engineering colleges in India

October 2, 2019 at 9:04 PM  
Blogger Rajesh said...

Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Course In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai

October 3, 2019 at 5:56 AM  
Blogger Rajesh said...

Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

October 3, 2019 at 5:56 AM  
Blogger Rajesh said...

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

October 3, 2019 at 5:57 AM  
Blogger Tyler Worgan said...

Hi, This is nice article you shared great information i have read it thanks for giving such a wonderful Blog for reader.
privacy fence san jose

October 3, 2019 at 9:35 PM  
Blogger jasminegates said...

I have read your article, it is very informative and helpful for me.concrete driveway repair port st lucie

October 4, 2019 at 4:09 AM  
Blogger Jackie Co Kad said...

Great Article
Final Year Project Domains for CSE
Final Year Project Centers in Chennai





JavaScript Training in Chennai
JavaScript Training in Chennai

October 4, 2019 at 5:02 AM  
Blogger Tyler Worgan said...

Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.
gate installation reno

October 5, 2019 at 12:09 AM  
Blogger Chris Hemsworth said...

The article is so informative. This is more helpful for our
best software testing training in chennai
best software testing training institute in chennai with placement
software testing training
courses

software testing training and placement
software testing training online
software testing class
software testing classes in chennai
best software testing courses in chennai
automation testing courses in chennai
Thanks for sharing.

October 5, 2019 at 2:54 AM  
Blogger Dana Milton said...

I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it.. bathtub refinishing and fiberglass expert san diego

October 5, 2019 at 3:51 AM  
Blogger Shop Sous Vide said...

Nice ideas shared.
tree service near me in jupiter

October 5, 2019 at 10:16 PM  
Blogger Naveen S said...

This is the first & best article to make me satisfied by presenting good content. I feel so happy and delighted. Thank you so much for this article.

Learn Best Digital Marketing Course in Chennai

Digital Marketing Course Training with Placement in Chennai

Best Big Data Course Training with Placement in Chennai

Big Data Analytics and Hadoop Course Training in Chennai

Best Data Science Course Training with Placement in Chennai

Data Science Online Certification Course Training in Chennai

Learn Best Android Development Course Training Institute in Chennai

Android Application Development Programming Course Training in Chennai

Learn Best AngularJS 4 Course Online Training and Placement Institute in Chennai

Learn Digital Marketing Course Training in Chennai

Digital Marketing Training with Placement Institute in Chennai

Learn Seo Course Training Institute in Chennai

Learn Social Media Marketing Training with Placement Institute in Chennai

October 7, 2019 at 4:05 AM  
Blogger Clark said...

thanks for sharing valuable articles.
tile resurfacing sacramento

October 8, 2019 at 12:52 AM  
Blogger Clark said...

Great idea shared.
fort lauderdale remodeling contractors

October 8, 2019 at 11:31 AM  
Blogger Clark said...

Best sharing.
water heater tune up sacramento

October 10, 2019 at 12:55 AM  
Blogger Clark said...

Nice post.
bathroom remodelers south miami

October 10, 2019 at 11:38 AM  
Blogger Clark said...

Thanks for sharing.
residential water heater services sacramento

October 11, 2019 at 11:53 PM  
Blogger Clark said...

Great post.
bathroom remodeling miami beach fl

October 12, 2019 at 3:46 AM  
Blogger Shop Sous Vide said...

Great post shared.
driveway gates orlando

October 13, 2019 at 12:11 AM  
Blogger Shop Sous Vide said...

Nice Information you have written here.
emergency tree services fort myers

October 13, 2019 at 5:00 AM  
Blogger deepika said...

great work.
spring mvc interview questions

October 13, 2019 at 11:38 PM  
Blogger Lovable vicky said...

Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Training In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai

October 13, 2019 at 11:40 PM  
Blogger Lovable vicky said...

Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

October 13, 2019 at 11:41 PM  
Blogger Unknown said...

Please refer below if you are looking for best project center in coimbatore

Hadoop Training in Coimbatore | Big Data Training in Coimbatore | Scrum Master Training in Coimbatore | R-Programming Training in Coimbatore | PMP Training In Coimbatore

Thank you for excellent article.

October 14, 2019 at 4:59 AM  
Blogger Unknown said...

Given article is very helpful and very useful for my admin, and pardon me permission to share articles here hopefully helped:
Erp In Chennai
IT Infrastructure Services
ERP software company in India
Mobile Application Development Company in India
ERP in India
Web development company in chennai

October 15, 2019 at 1:35 AM  
Blogger Shop Sous Vide said...

Awesome.
lantana tree service

October 16, 2019 at 4:43 AM  
Blogger Clark said...

great post.
kitchen remodel broward county

October 20, 2019 at 5:09 AM  
Blogger Clark said...

Nice post.
water heater expansion tank jacksonville

October 20, 2019 at 10:59 AM  
Blogger Clark said...

thanks for sharing valuable articles.
gutter cleaning treasure coast

October 20, 2019 at 11:50 PM  
Blogger Brown kris said...

Good job and thanks for sharing such a good blog.
kandol lake

October 21, 2019 at 2:46 AM  
Blogger Clark said...

Thanks for sharing.
natural gas water heaters wesley chapel

October 21, 2019 at 8:32 AM  
Blogger zuan said...

I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
Web Designing Course in Chennai | Web Designing Training in Chennai
web designing institute in chennai | Web Designing Training Institute in Chennai
Web Designing Training Institute in Chennai | web design training class in chennai | web designing course in chennai with placement
Mobile Application Development Courses in chennai

October 21, 2019 at 11:56 PM  
«Oldest ‹Older 201 – 251 of 251

Post a Comment

Subscribe to Post Comments [Atom]

<< Home