Reputation: 11
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
Upvotes: 1
Views: 98
Reputation: 269852
If v is a vector then for each i we have a separate equation to solve
t[i] = v[i]*(1+theta*(1-v[i])*(1-2*u[i]))), i = 1, ..., 10
so solve each separately and extract the roots:
sapply(seq_along(u), \(i) uniroot(\(v) f(u[i], v) - t[i], 0:1)$root)
giving
[1] 0.39692788 0.78029920 0.45297128 0.89012910 0.90697036 0.07238876
[7] 0.46491197 0.82686074 0.50843227 0.56812761
or if you want to retain the entire output from each optimization
sapply(seq_along(u), \(i) unlist(uniroot(\(v) f(u[i], v) - t[i], 0:1)))
giving
[,1] [,2] [,3] [,4] [,5]
root 3.969279e-01 7.802992e-01 4.529713e-01 8.901291e-01 9.069704e-01
f.root -4.643955e-06 -5.900526e-06 -5.570426e-06 8.196328e-06 6.355961e-06
iter 5.000000e+00 3.000000e+00 4.000000e+00 3.000000e+00 5.000000e+00
init.it NA NA NA NA NA
estim.prec 6.103516e-05 6.103516e-05 6.103516e-05 6.103516e-05 6.103516e-05
[,6] [,7] [,8] [,9] [,10]
root 7.238876e-02 4.649120e-01 8.268607e-01 5.084323e-01 5.681276e-01
f.root -1.543902e-05 -2.805944e-05 1.395974e-06 4.842540e-06 -3.522527e-06
iter 5.000000e+00 4.000000e+00 6.000000e+00 4.000000e+00 5.000000e+00
init.it NA NA NA NA NA
estim.prec 6.103516e-05 6.103516e-05 6.103516e-05 6.103516e-05 6.103516e-05
The inputs in the question are not reproducible due to the use of random numbers so to be clear we used these values.
u <- c(0.956833345349878, 0.453334156190977, 0.677570635452867,
0.572633401956409,
0.102924682665616, 0.899824970401824, 0.24608773435466, 0.0420595335308462,
0.327920719282702, 0.954503649147227)
t <- c(0.287577520124614, 0.788305135443807, 0.4089769218117,
0.883017404004931,
0.940467284293845, 0.0455564993899316, 0.528105488047004, 0.892419044394046,
0.551435014465824, 0.456614735303447)
theta <- 0.5
Upvotes: 0