Jump to content

generate random number with variable probability


grilldor

Recommended Posts

Hi all, what im trying to achieve is to generate a random number from 0.1 to 1.0 with a better probability to get a 0.5 to 0.7 result.
[code]
$possi = array("0.1", "0.2", "0.2", "0.3", "0.3", "0.4", "0.4", "0.5", "0.5", "0.5", "0.6", "0.6", "0.6", "0.6", "0.6", "0.7", "0.7", "0.7", "0.8", "0.8", "0.9", "1.0");
$decide = rand(0,21);
$damage = 500 * $possi[$decide];
echo $damage;
[/code]

this works, great. problem is i would need 2 decimals to the numbers and I would need a way to better generate this without going on and putting 0.61, 0.62, 0.63, 0.64 etc... Do you guys have anything better to suggest?

EDIT: A 3 decimal version would be even more appreciated!
You can generate the second decimal place seperately, then add them together.

Alternatively you could express the probability as a function of the value being generated, and generate your array according to that function.  But generating the second place seperately seems simpler :)
oops i have a little problem though, generating 6 is the same as generating 60 for the 2 extra decimals :

for example. array result is : 0.4 i then add my generated number from 0 to 99
so if i get 6 it does:
0.46
if i get 60 it does :
0.460 which is the same...
is there a direct way to generate the numbers with the 0 in front or do i need to do an if <10 add 0?
[quote author=grilldor link=topic=114085.msg464021#msg464021 date=1162863868]A 3 decimal version would be even more appreciated!
[/quote]

You could do like this:
[code=php:0]<?php

$array = range(1, 999);

foreach($array as $key => $value)
$array[$key] = '0.' . str_pad($value, 3, '0', STR_PAD_LEFT);

print_r($array);

?>[/code]
I would do it like this:

[code]$possi = array("0.1", "0.2", "0.2", "0.3", "0.3", "0.4", "0.4", "0.5", "0.5", "0.5", "0.6", "0.6", "0.6", "0.6", "0.6", "0.7", "0.7", "0.7", "0.8", "0.8", "0.9", "1.0");
$decide = rand(0,21);
$extra = rand(0,99) / 1000.0;
$damage = 500 * ($possi[$decide] + $extra);
echo $damage;[/code]

By doing it mathematically, zero-padding isn't an issue.  This assumes you're ok with an even probability distribution for the extra 2 digits.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.