簡體   English   中英

使用 uniroot 更新函數中的值

[英]Update value in function using uniroot

我想根據 R 中 uniroot 的結果更新函數中的特定值。

例如,如果我試圖求解 x,其中 s=60000 和 t=19.95,我有:

(sx-0.05*(0.04*x + 1810.726 - mu(40,t)*(sx)))=59789

對於下一次迭代,我想更新 s 的值,使 s=59789,以及 t 的值,使 t=19.90。 重復,這應該一直更新到 t=0,t 向下 0.05 步。 因此,399 次迭代,因為 19.95/0.05 = 399。

(mu 只是一個預定義函數,例如 mu(40, 19.95) = 0.003204。)

這是一些示例代碼:

s <- 60000
t <- 19.95

f <- function(x) (s - x - 0.05*(0.04*x + 1810.726 - mu(40, t)*(s - x)))

uniroot(f, lower=0.1, upper=100000000)$root

誰能給我一些關於如何實施的建議?


mu()給出如下:

mu <- function(x, t) {
  A <- .00022
  B <- 2.7*10^(-6)
  c <- 1.124
  mutemp <- A + B*c^(x + t)
  out <- ifelse(t <= 2, 0.9^(2 - t)*mutemp, mutemp)
  out
}

預期結果應如下所示:

t x
0 0.0000
1 1853.8638 11 26882.9244
2 3817.7860 12 30070.8515
3 5894.9409 13 33384.7327
4 8088.4838 14 36823.9198
5 10400.9021 15 40387.3491
6 12834.5166 16 44073.5260
7 15391.4745 17 47880.5110
8 18073.7445 18 51805.9074
9 20883.1160 19 55846.8507
10 23821.2011 20 60000.0000

59789的值對應於V_{19.95} = 59789V_{20} = 60000是給定的起始值。

這個 for 循環可能會有所幫助。

1. 運行所有代碼

s <- 60000
t <- 20

mu <- function(x, t) {
  A <- .00022
  B <- 2.7*10^(-6)
  c <- 1.124
  mutemp <- A + B*c^(x + t)
  out <- ifelse(t <= 2, 0.9^(2 - t)*mutemp, mutemp)
  out}

f <- function(x) (s - x - 0.05*(0.04*x + 1810.726 - mu(40, t)*(s - x)))

2.運行下面的for循環進行迭代

2.1 預定義結果的長度。 在你的情況下是 400 (t/0.05 = 400)。

output <- vector(mode = "numeric", length = t/0.05)

2.2 從 1 到 400 運行 for 循環。將每個 uniroot 結果保存到步驟 2.1,然后相應地重新分配 s 和 t。

for (i in 1:400) {
  output[i] <- uniroot(f, lower=0.1, upper=100000000)$root
  s <- output[i]
  t <- 20 - i * 0.05
}

3. 檢查結果

output

希望這會有所幫助。

您可以在定義seq t上使用vapply

s <- 6e4
tseq <- seq.int(19.95, 0, -.05)

x <- vapply(tseq, \(t) {
  s <<- uniroot(\(x) (s - x - 0.05*(0.04*x + 1810.726 - mu(40, t)*(s - x))), lower=0.1, upper=100000000)$root
}, numeric(1L))

請注意, <<-在全局環境中更改s ,並在最后獲取最后一個值。

s
# [1] 2072.275

res <- cbind(t=tseq, x)

head(res)
#          t        x
# [1,] 19.95 59789.92
# [2,] 19.90 59580.25
# [3,] 19.85 59371.01
# [4,] 19.80 59162.18
# [5,] 19.75 58953.77
# [6,] 19.70 58745.77

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM