How to create a probability density function and expectation in r?

Task:

Eric has a friend, Ernie. Suppose that two flies sit in independent places, evenly distributed on the surface of the globes. Let D denote the Euclidean distance between Eric and Ernie (i.e., On a straight line along the inside of the globe).

Make a hypothesis about the probability density function D and give an estimate of its expected value, E (D).

So far I have created a function to create two points on the surface of the globe, but I'm not sure what to do next:

sample3d <- function(2)
  {
  df <- data.frame()
  while(n > 0){
    x <- runif(1,-1,1)
    y <- runif(1,-1,1)
    z <- runif(1,-1,1)
    r <- x^2 + y^2 + z^2
    if (r < 1){
      u <- sqrt(x^2+y^2+z^2)
      vector = data.frame(x = x/u,y = y/u, z = z/u)
      df <- rbind(vector,df)
      n = n- 1
    }
  }
  df
}
E <- sample3d(2)
+4
source share
1 answer

This is an interesting problem. I will describe a computational approach; I will leave the math up to you.

  • First we fix a random seed for reproducibility.

    set.seed(2018);
    
  • 10^4 .

    sample3d <- function(n = 100) {
      df <- data.frame();
      while(n > 0) {
        x <- runif(1,-1,1)
        y <- runif(1,-1,1)
        z <- runif(1,-1,1)
        r <- x^2 + y^2 + z^2
        if (r < 1) {
          u <- sqrt(x^2 + y^2 + z^2)
          vector = data.frame(x = x/u,y = y/u, z = z/u)
          df <- rbind(vector,df)
          n = n- 1
        }
      }
      df
    }
    df <- sample3d(10^4);
    

    , sample3d , .

  • 2 df, ( dist) N = 10^4 .

    # Sample 2 points randomly from df, repeat N times
    N <- 10^4;
    dist <- replicate(N, dist(df[sample(1:nrow(df), 2), ]));
    

    @JosephWood, N = 10^4 . bootstrap . N -> infinity , , () ( Bootstrap). 1/sqrt(N), N = 10^4 1%.

  • :

    # Let plot the distribution
    ggplot(data.frame(x = dist), aes(x)) + geom_histogram(bins = 50);
    

enter image description here

  1. , .

    # Mean
    mean(dist);
    #[1] 1.333021
    
    # Median
    median(dist);
    #[1] 1.41602
    

    :

    mean.th = 4/3
    median.th = sqrt(2)
    
+2

Source: https://habr.com/ru/post/1695081/


All Articles