r - 模拟中的 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 将找不到解决方案。有谁知道在这种情况下我能做什么?提前致谢!
解决方案
也许我误解了,但你不能直接找到答案吗?
z_zero <- 1-sum(price_b)/sum(price_a)
x <- cumsum_cost(z_zero)
tail(x,1)
#> [1] 6.093615e-11
推荐阅读
- java - 打包的 Spring Boot 应用程序不会将其余 api 错误解析为消息
- javascript - 如何让幻灯片默认显示?
- python - python中的plt.hist函数没有显示正确的指数分布
- pandas - 如何对 Ames Housing 数据集中的两个类别进行列转换?
- sql - 如何返回前 x 不同的销售额总和?
- api - 当 return_type=popular 时,Twitter API v1.1 不返回主题标签。如何得到它们?
- visual-studio-code - 如何在 VSCode 编辑器上方添加内容
- javascript - React 中的图像数据在哪里?
- node.js - 为什么 Tenor GIF 会在嵌入中产生 Discord 便便图像?
- gdb - 使用 gdb-multiarch 和 qemu 调试 aarch64,无法 Ctrl+C/SIGINT