Reputation: 320
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, (Using random function) the value increases or decreases by 20%. So, after 1 year, if I check my bank accounts, approximately 50% accounts should have balance greater than $100.
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.
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);
{increased: 107, decreased: 693}
Is this a javascript issue or there's something wrong with my algorithm? Please provide your inputs.
Upvotes: 0
Views: 338
Reputation: 781059
This is because increasing and decreasing by percentages don't undo each other equally. A percentage of a high balance is larger than the same percentage of a low balance, so the losses tend to exceed the gains.
Just consider 2 days, and suppose the price increases by 20% one day, and decreases by 20% the other day. After day 1 the balance will be 120
, after day 2 the balance will be 96
; it doesn't return to 100
(the result is the same if the order of the days is swapped, since multiplication is commutative and associative). So even though you have an equal number of increases and decreases, the final result is a decrease.
If you change it so that the increases are fixed amounts, such as a random amount from -5
to 5
, then you get the expected result of a roughly equal number of increases and decreases.
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 -5 to 5
let delta = (Math.random() - 0.5) * 10;
// console.log("Delta", delta);
prices[j] += delta;
}
}
for (let p of prices) {
if (p > 100) {
result.increased++;
} else {
result.decreased++;
}
}
}
console.log(result);
Upvotes: 4