Suppose f(u,v)=v(1+theta(1-v)(1-2u))=t, where u and t are uniform(0,1) random samples and theta=0.5. How can I optimize the value of v in R?
I tried to make a code using uniroot
in r, but it gave me an error. How can I optimize the value of v?
Here is what I tried so far:
t <- runif(10,0,1)
u <- runif(10,0,1)
theta <- 0.5
f <- function(u,v) {
return(v*(1+theta*(1-v)*(1-2*u)))
}
equation <- function(v) {
return(f(u,v)-t)
}
solution <- uniroot(equation,interval=c(0,1))
v <- solution$root
And the error message:
Error in if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
the condition has length > 1
If v is a vector then for each i we have a separate equation to solve
so solve each separately and extract the roots:
giving
or if you want to retain the entire output from each optimization
giving
Note
The inputs in the question are not reproducible due to the use of random numbers so to be clear we used these values.