score324
score324

Reputation: 717

Solve for an unknown value in R

I have an equation ln(1 - P) * ln(1 - X2/d) = ln(1 - Q) * ln(1 - X1/d). I want to determine the dvlaue. I wrote the following r code.

Q = 0.75
P = 0.5
X2 = 5.57665
X1 = 1.473618
fun = function(d) (log(1-P)*log(1 - X2/d) - log(1 - Q)*log(1 - X1/d))^2
optimize(fun, c(0, 1000), maximum = TRUE, tol = 1e-10)

Does the above code correct? I set the interval c(0, 1000). How to select the appropriate one? Also, is there any other way to find d? Thanks.

Upvotes: 0

Views: 418

Answers (1)

LMc
LMc

Reputation: 18622

Well for starters, check if there is even a solution to this equation, which is luckily in this x-range:

library(ggplot2)

f1 <- function(d) log(1-P)*log(1-X2/d)
f2 <- function(d) log(1-Q)*log(1-X1/d)

(p <- ggplot() +
  xlim(-12, 12) + 
  ylim(-10, 10) +
  geom_function(fun = f1, n = 1E4, aes(color = "f1")) +
  geom_function(fun = f2, n = 1E4, aes(color = "f2")))

enter image description here

Note that there is a vertical asymptote at x = 0 and a horizontal asymptote at y = 0. This will be helpful setting the search interval.

Next, you need to have your equation correct. I'm not sure where the ^2 came from. Moving the LHS of the equation to the RHS you get this function:

f <- function(d) log(1-P)*log(1-X2/d) - (log(1-Q)*log(1-X1/d))

That we can solve with the uniroot function from base R:

(eq <- uniroot(f, lower = -10, upper = -0.01))
$root
[1] -0.8258847

$f.root
[1] -5.59396e-06

$iter
[1] 10

$init.it
[1] NA

$estim.prec
[1] 6.103516e-05

And to confirm with the plot:

p + 
  geom_point(data = data.frame(x = eq$root, y = f1(eq$root)), aes(x = x, y = y))

Note y could have been found with either f1 or f2 since they're equal at this point. Also this value was found through optimization so there is some error as shown by eq$estim.prec.

enter image description here

Upvotes: 2

Related Questions