vendredi 12 juin 2020

Get balanced random values in Javascript

Scenario

I have implemented a fictional scenario to better explain the problem. I have 800 bank accounts, in each, I have invested $100 for a duration of 1 year. Every day, there is a 20% chance (Using random function) of increase or decrease in currency value. So, after 1 year, if I check my bank accounts, approximately 50% accounts should have balance greater than $100.

Issue

Using javascript built-in random function, I am getting 12% to 16% accounts where value has increased and remaining where value has decreased after multiple runs.

Code

let prices = [100, 100, 100, 100, 100, 100, 100, 100];
let days = 365;
let experiment_runs = 100;
let result = {
  increased: 0,
  decreased: 0
}

for (let e = 0; e < experiment_runs; e++) {
  prices = [100, 100, 100, 100, 100, 100, 100, 100];
  for (let i = 0; i < days; i++) {
    for (let j = 0; j < prices.length; j++) {
      // Change price by 20%
      let delta = (Math.random() - 0.5) * 0.4 * prices[j];
      // console.log("Delta", delta);
      prices[j] += delta;
    }
  }

  console.log(prices);

  for (let p of prices) {
    if (p > 100) {
      result.increased++;
    } else {
      result.decreased++;
    }
  }
}

console.log(result);

Output

{increased: 107, decreased: 693}

Is this a javascript issue or there's something wrong with my algorithm? Please provide your inputs.




Aucun commentaire:

Enregistrer un commentaire