runiroot

Uniroot in simulations


I'm trying to find the value that generates the cumulative sum of a function to be 0 (or the closest value to 0). I have a simple ecuation: x - y(1-z) where z is the key variable. The problem is that x and y are simulated, so they don't remain constant. Here is the reproducible example:

set.seed(96)
#Create a dataframe with x and y. x = price_b;  y = price_a
month <- 1:120 #10 years
price_a <- runif(120, min = 9500, max = 12000) #random values for price_a
price_b <- runif(120, min = 4500, max = 6500) #random values for price_b
data <- data.frame(month, price_a, price_b)

#Function to calculate the stabilization cost
cumsum_cost <- function(z) {
  cost <- price_b - price_a*(1-z)
  cumsum <- cumsum(cost)
}

#Use function with z= 0.5 and create a column with the results
cumulative_cost <- cumsum_cost(0.5)
data$stabilization_cost <- cumulative_cost

#Try to use uniroot to find which value of z generates the last value of cumulative_cost to be 0.
uniroot(cumsum_cost, lower =0, upper = 1)

I'm aware that since the values x and y of the function are constantly changing, uniroot will not find a solution. Does anybody knows what could I do in this case? Thanks in advance!


Solution

  • Maybe I've misunderstood but can't you find the answer directly?

    z_zero <- 1-sum(price_b)/sum(price_a)
    x <- cumsum_cost(z_zero)
    tail(x,1)
    #> [1] 6.093615e-11