简体   繁体   中英

Need help interpreting this code

So this code was handed out in our school, its one of many examples (model of rolling a fair dice).

x<-runif(1)
y<-as.double(x<=c(1/6,2/6,3/6,4/6,5/6,1))*(1:6)
x<-min(y[y>0])  

Im having trouble understanding the relation of this code and rolling a dice.

So the first line generates 1 randomly uniform distributed number x between 0 and 1. In the second line we put a condition into x: If its less than 1 of the components of the vector (1/6,2/6,3/6,4/6,5/6,1) we get a TRUE=1 , else FALSE=0.

And then this result is multiplied by the vector (1,2,3,4,5,6). Lastly we take the minimum value of that vector product (has to be greater than zero).

I cant get the intuition behind this. Would someone here mind to explain the relation of this code to rolling a dice in real life. Im confused..

So for rolling a dice each number has the same probability of 1/6 to appear.

Now what is done here, is to simulate rolling a dice.

Therefore in the first line a random number between 0 and 1 is generated.

The intervals it is compared to are all equally sized and they have a length of 1/6. There for, for x to lie in one of these intervals the probability is again 1/6. So what is done then in the third line, is to look up in which interval x has fallen.

Lets do an example: Supposed x is 0.25. Then the vector of the second line would look like this:

FALSE, TRUE, TRUE, TRUE , TRUE, TRUE 

With the multiplication you get:

0, 2, 3, 4, 5, 6

Therefore at the end x is equal to 2.

So at the end x is supposed to be the number the dice is showing

Benjamin is right basically your code is saying

If runif(1) = 0 to 1/6 = die roll = 1

runif(1) = 1/6 to 2/6 = die roll = 2

runif(1) = 2/6 to 3/6 = die roll = 3

etc

Because the second line returns a vector of results the x<-min(y[y>0]) just returns the first positive which is your die roll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM