S
S
spaceatmoon2019-02-26 11:54:43
Programming
spaceatmoon, 2019-02-26 11:54:43

How to correctly express the probability of success in code?

Is there a general approach to turning a percentage of a probability into the result of an action in programming?
Let's say I bought a lottery ticket with a 50% chance of winning. How do I turn this into a function that gives yes or no based on that percentage?
Would it be correct to convert percentages to fractions, and if the numerator falls on the randomizer, then the function returns - True?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lander, 2019-02-26
@spaceatmoon

function getSuccesByСhance($chance)
{
    return mt_rand(0, 100) <= $chance;
};

var_dump(getSuccesByСhance(30)); //false
var_dump(getSuccesByСhance(30)); //true
var_dump(getSuccesByСhance(30)); //true
var_dump(getSuccesByСhance(30)); //false
var_dump(getSuccesByСhance(30)); //true
var_dump(getSuccesByСhance(30)); //false
var_dump(getSuccesByСhance(30)); //false
var_dump(getSuccesByСhance(30)); //false
var_dump(getSuccesByСhance(30)); //false
var_dump(getSuccesByСhance(30)); //false

upd: I think it's clear that this is php.

A
Alex, 2019-02-26
@Kozack

In the case of JavaScript. (chance in the range [0; 1))

function getResult(chance) {
    return Math.random() < chance
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question