mardi 28 mars 2017

probability modifiers for Math.random()

I'd like to know what the best or most accepted method of creating probabilities is. I've done some research and found some interesting questions and answers on the Math.random() topic such as:

How random is JavaScript's Math.random?

and

Generating random whole numbers in JavaScript in a specific range?

I'm looking for a simple way to modify the probability that a value will be true or not using Math.random()

For example, I know that Math.floor(Math.random() * 2) is a useful method for generating a 1 nearly 50% of the time:

-Math.random() generates a random number between 0 (inclusive) and 1 (exclusive)

-If the number generated is < 0.5, this number multiplied by 2 will still be less than 1, so this number .floor() returns a 0

-If the number generated is > 0.5, this number multiplied by 2 will be greater than 1, so this number .floor() returns a 1

I wanted to skew the probability of getting a 1 using a "modifier" and this is as close as I have to come to getting the desired probability...

Every time you run the code snippet the console prints the percentage of hits. As you can see they are almost accurate, but not quite. I came up with the exponent modifying function by trial and error. Is there any way I can make this more accurate?

var youHit = Math.floor(Math.random() * 2);
var totalTries = 0;
var hits = 0;

var pointNine = 0.9; // you want 90% of tries to hit
var pointEight = 0.8;// you want 80% of tries to hit 
var pointSeven = 0.7;// you want 70% of tries to hit
  
function probCheck(modifier) {
  var exponent = 1 + (1 - modifier) + (1 - modifier)*10;
  for (var x = 0; x < 100; x++) {
     youHit = Math.floor((Math.pow(modifier, exponent)) + (Math.random() * 2));
     totalTries += 1;
     if (youHit) {
        hits += 1;
     } 
  }
  console.log("final probability check: " + hits / totalTries);
};

 probCheck(pointNine);
 probCheck(pointEight);
 probCheck(pointSeven);
<script src="http://ift.tt/1oMJErh"></script>



Aucun commentaire:

Enregistrer un commentaire