0

Just some smaller changes which do not need to be considered.

  • 1
    Please do not vandalise questions, especially not when it has received answers. Posts here are meant to be shared with future visitors. – Martijn Pieters Dec 24 '22 at 23:12

2 Answers2

2

This for loop may be helpful.

1. Run all of your codes

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. Run the for loop below for iteration

2.1 Predefine the length of the outcome. In your case is 400 (t/0.05 = 400).

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

2.2 Run through the for loop from 1 to 400. Save each uniroot result to step 2.1, and then reassign both s and t accordingly.

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

3. Inspect the result

output

Hope this is helpful.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Grasshopper_NZ
  • 302
  • 1
  • 10
1

You could use vapply on a defined t sequence.

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))

Note, that <<- changes s in the global environment, and at the end gets the last value.

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
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • @KalleBlomkvist You have something different than `t <- 19.95`, notice that I have changed the code `seq.int(19.95, 0, -.05)`. – jay.sf Dec 22 '22 at 11:45