1

At first, I have two functions like the following:

ef <- function(x, a){
  if(a == 0){
    return(x)
  } else {
    return(1-exp(-a*(5+x)))
  }
}
f1 <- function(x) ef(x,a)-0.75*ef(2.5,a)-0.25*ef(-1,a)

If a is 2 (i.e. a <- 2), then the root should be:

uniroot(f1, c(-5, 0), tol = 0.0001)$root

Now my question is how to calculate the root of x of the function when a change from 0.05 to 3 by 0.05?

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Xiaohan Lu
  • 13
  • 3

1 Answers1

0

I think it's more flexible to put a into f1() as an argument.

f1 <- function(x, a) ef(x, a)-0.75*ef(2.5, a)-0.25*ef(-1, a)

Then use sapply() to operate each value in the sequence seq(0.05, 3, 0.05):

sapply(seq(0.05, 3, 0.05), function(A){
  uniroot(f1, c(-10, 10), tol = 0.0001, extendInt = "yes", a = A)$root
})

# [1]  1.565924900  1.503659791  1.438426382  1.370549617  1.300423929
# [6]  1.228478774  1.155273229  1.081323809  1.007194271  0.933431003 ...

The argument extendInt = "yes" can conquer the error when f1() does not have different signs at the endpoints. In addition, I prefer apply family rather than a for loop in this case. You can read this for the reason.


Edit: for loop solution

a <- seq(0.05, 3, 0.05)
root <- numeric()
for(i in 1:length(a)){
  root[i] <- uniroot(f1, c(-10, 10), tol = 0.0001, extendInt = "yes", a = a[i])$root
}

At the end of the loop, the variable root will store all the roots. You can check whether the outputs of the two solutions are equal.

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
  • Can I ask why you set function(A)? Why is A? – Xiaohan Lu Feb 09 '19 at 19:09
  • The `A` in the function of `sapply()` is an argument I set to represent each value in the sequence 0.05 ~ 3. You can also use other texts but remember to change the argument inside. – Darren Tsai Feb 09 '19 at 19:47