Tower
Tower

Reputation: 102785

Converting random byte (0-255) to a float in PHP?

I am reading random bytes from /dev/urandom, and I want to make a random float out of it/them. How would I do this? I can convert the byte to a number with ord(), and it's between 0 and 255.

It's obvious that 255 is 1.0, 127 is 0.5 and 0 is 0.0, but how do I calculate the rest? Also, I think one byte is not enough to give lots of precision? How many bytes should I use for this?

Upvotes: 0

Views: 904

Answers (4)

Joey
Joey

Reputation: 354456

If you want the full precision float can offer, then you'll need 24 bits or three bytes:

$float = ($b1 | ($b2 << 8) | ($b3 << 16)) / (float)(1 << 24);

However, PHP's documentation is a little fuzzy on the details so if you need a double which is 64 bits long instead of float's 32 bits, then you'll need 53 bits.

Upvotes: 0

Paul Tarjan
Paul Tarjan

Reputation: 50602

Umm, do you just want a random sequence of numbers? If so, just use http://php.net/mt_rand

$int = mt_rand(0, 1000);
$float = mt_rand(0, 1000) / 1000.0;
$float_more_precise = mt_rand(0, 100000) / 100000.0;

Upvotes: 2

pavium
pavium

Reputation: 15118

Try the simple linear relationship

$f = $r / 255.0;

where $r is the random byte, and $f is the random float.

This way, when $r=255, $f is 1.0 and when $r=127, $f is 0.498

to get 0.5 for r=127 would require a different relationship.

Upvotes: 2

Gausie
Gausie

Reputation: 4359

Since you want 127 to be 0.5, I imagine you want

$float = round($byte/255,1)

Upvotes: 0

Related Questions