Home > OS >  Writing recursion function for probability
Writing recursion function for probability

Time:12-11

I am trying to find where the probability reaches a certain point; then, the function will return the value responsible for this probability.

The function I wrote takes two arguments p represents the number of CPUs q the number of jobs processed by each CPU

The function wants to optimise the number of CPUs in a server that will guarantee a 0.9 probability that each CPU will handle only one job simultaneously. Therefore, the number of processors (p) needs to be > the number of jobs (q).

opcpu <- function(p,q){
  if (p < q){
    paste("The number of processors should be",q," or more")
  } else {
    prob = prod(p:(p-(q-1)))/p^q
    while (prob < 0.9){
      p = p   1
      opcpu(p,q)
    }
    return(p)
  }
}

I wrote the function as a recursion function. But it seems there is something wrong.

I tried to run the function, but it is not working. Solving the problem by trial and error gives that p = 631 when q = 12.

CodePudding user response:

You’re on the right track. Try using if instead of while, and returning either p or a recursive call:

opcpu <- function(p,q) {
  if (p < q) {
    stop("The number of processors should be", q, " or more")
  }
  prob <- prod(p:(p-(q-1)))/p^q
  if (prob < 0.9) {
    opcpu(p 1,q)
  } else {
    p
  }
}

opcpu(12,12)
# 631

Or you could use while instead of recursion:

opcpu <- function(p,q) {
  if (p < q) {
    stop("The number of processors should be", q, " or more")
  }
  prob <- prod(p:(p-(q-1)))/p^q
  while (prob < 0.9){
    p <- p   1
    prob <- prod(p:(p-(q-1)))/p^q
  }
  p
}

opcpu(12,12)
# 631

Note, I changed your paste() to stop(), since it seems you’re trying to indicate that p < q isn’t valid input. Another option would be to just start testing at p = q if the input is missing or less than q:

opcpu <- function(p,q) {
  if (missing(p) || p < q) p <- q
  prob <- prod(p:(p-(q-1)))/p^q
  if (prob < 0.9) {
    opcpu(p 1,q)
  } else {
    p
  }
}

opcpu(q = 12)
# 631
  • Related