GGio
GGio

Reputation: 7653

Pick a number based on probability in floating number PHP

I am trying to create a dice game where you are given a 6 sided dice and you roll but the probabilities of each side is predefined (not fair).

Example:

Side    Probability

1       3.63098
2       18.38200
3       10.59424
4       3.87055
5       13.66651
6       49.85572

Total:  100

So Side 6 should roll most often than any other. I've tried the following approach:

3.63098 + 18.38200 + 10.59424 + 3.87055 + 13.66651 + 49.85572 = 100

and generate a random number: rand(0, 100) and pick a number based on where it lied.

However it does not really work with floating numbers, max probability does not have to be 100 it can be 23.994 and will be distributed randomly to 6 sides.

Please suggest an algorithm to use or where to look for algorithms, I'm not asking to write code for me just need to research but dont know what to look for.

Upvotes: 1

Views: 495

Answers (2)

Vikram Bhat
Vikram Bhat

Reputation: 6246

First do normalization of probabilty to lie within [0,1]

normalizes prob(p) = value(p)/(sum of all values)

then find range of values of each variable for example

1 => 0.2
2 => 0.3
3 => 0.1
4 => 0.2
5 => 0.1
6 => 0.1

then ranges will be:-

1 =>[0,0.2]
2 =>(0.2,0.5]
3 =>(0.5,0.6]
4 =>(0.6,0.8]
5 =>(0.8,0.9]
6 =>(0.9,1.0]

Then for a dice roll generate a random float in range [0,1]

Find the range in which it is enclosed

eg . random float = 0.37 then side on top will be 2

Upvotes: 2

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

You can generate a random number between 0 and RAND_MAX.

Then scale each probability to RAND_MAX by dividing by 100 and multiplying by RAND_MAX. You can get more accurate probabilistic outcomes.

OR

Just divide the generated random number by RAND_MAX and check which range of [0,1] it lies.

Upvotes: 3

Related Questions