jeudi 22 août 2019

Choose variable based on weighted probability

I have a list of variables with their weighted probability, as below:

Cloudy: 0.25
Sunny and warm: 0.25
Dry and cold: 0.125
Wet and cold: 0.25
Wet and warm: 0.375
Stormy/rainy: 0

In google sheets I am using the following function to select a variable based on these probabilities

=INDEX('WeatherChoices'!A2:A7,COUNTIF('WeatherChoices'!D2:D7,"<="&RAND())+1)

Where A2:A7 is the list of weather types and D2:D7 is the cumulative probabilities.

I am now trying to replicate this as a google script function but can't figure out an alternative to nested IF statements. I.e. generate a random number and if between two of the cumulative values choose the variable.

Is there are more elegant way of doing this in one step?

I have looked through the documentation but couldn't find anything other than the .random() function.




Aucun commentaire:

Enregistrer un commentaire