首页 > 解决方案 > 模拟中的 Uniroot

问题描述

我试图找到生成函数的累积和为 0(或最接近 0 的值)的值。我有一个简单的计算:x - y(1-z) 其中 z 是关键变量。问题是 x 和 y 是模拟的,因此它们不会保持不变。这是可重现的示例:

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)

我知道由于函数的值 x 和 y 不断变化,uniroot 将找不到解决方案。有谁知道在这种情况下我能做什么?提前致谢!

标签: runiroot

解决方案


也许我误解了,但你不能直接找到答案吗?

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

推荐阅读