Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

in R. Consider the example of calculating the probability of having "at least" two…

  1. User

    in R. Consider the example of calculating the probability of having "at least" two people having the same birthday in a class size of 40. Write an R function p(n,x) that will calculate this probability as a function of class size, n, and the number of people, x, having the same birthday (at least x people). Draw, in R, a 3D graph showing this probability as a function of n and x.

  2. Assistant

    Here is an R function p(n,x) that calculates the probability of having at least x people with the same birthday in a class size of n:

    p <- function(n, x) {
      if(n <= 0 | x <= 0 | x > n) {
        return(0)
      }
      
      total_prob <- 0
      for(i in x:n) {
        i_prob <- factorial(n) / (factorial(i) * factorial(n-i)) * (1/365^i) * (364/365)^(n-i)
        total_prob <- total_prob + i_prob
      }
      
      return(total_prob)
    }
    

    Now, let's create a 3D graph showing this probability as a function of n and x:

    library(plot3D)
    
    n <- seq(10, 40, by = 1)
    x <- seq(2, 10, by = 1)
    
    prob_matrix <- outer(n, x, FUN = function(n, x) p(n, x))
    persp3D(n, x, prob_matrix, theta = -30, phi = 30, col = "lightblue", 
            xlab = "Class Size (n)", ylab = "Number of People (x)", zlab = "Probability")