samedi 21 août 2021

Generate random number that fluctuates by F within range R

I want to generate a random number within this range: [0.79, 2.7]

Every time I generate a number I want to store its value so that next time I generate a new number its absolute difference (compared to the previous one) is never greater than 0.01.

What I'm trying to simulate is the fluctuation of the value of a cryptocoin in 0.01 steps

I have come up with this method:

const MIN = 0.79
const MAX = 2.7
const DIFF = 0.01
const INTERVAL = 1000

let previous = undefined 

function getRandom() {
  let current = Math.random() * (MAX - MIN) + MIN;
    
  if (Math.abs(current - (previous || current)) > DIFF){
    return getRandom()
  } else {
    previous = current
    return current
  }
}

setInterval(() => {
  console.log(getRandom())
}, INTERVAL)

It works, as in, the MIN, MAX and DIFF restrictions are applied. However, the values I get seem to always fluctuate around the very first random number that will be generated. So if the first random number I get is e.g. 2.34 I will then start getting:

2.338268500646769
2.3415300555082035
2.3438416874302623
2.3475220779731107
2.3552742162452693
2.353575076772505
2.3502457929806693
2.3561300642858143
2.353045875361622
2.3592926605489004
2.360013424409005
2.3520769942926023

Whereas, what I want is for them to fluctuate all the way from 0.79 to 2.7 with 0.01 steps but randomly nevertheless. So the value of a cryptocoin might start going up for a X seconds, then down for Y seconds, then further down for another Z seconds then all of a sudden up for T seconds etc..

Can you think of an algorithm to mimic that ?

Thank you in advance for your help.




Aucun commentaire:

Enregistrer un commentaire