# Why "uniroot()" confuses the input values but "optimize()" doesn't?

I'm wondering why in the following two parallel R code blocks, `uniroot()` gives an incorrect answer (i.e., `1e+07`) while `optimize()` finds the correct answer (i.e., `336.3954`).

Both blocks of code try to solve for `df2` such that `y = .15`.

What is the reason behind `uniroot`'s failure and `optimize`'s success?

``````    ############# Code Block 1 (with uniroot):

alpha = c(.025, .975); df1 = 3; peta = .3 # input values

f <- function(alpha, q, df1, df2, ncp){    # Objective function
alpha - suppressWarnings(pf((peta / df1) / ((1 - peta)/df2), df1, df2, ncp, lower.tail = FALSE))
}

ncp <- function(df2){                    # root finding
b <- sapply(c(alpha[1], alpha[2]),
function(x) uniroot(f, c(0, 1e7), alpha = x, q = peta, df1 = df1, df2 = df2)[[1]])

b / (b + (df2 + 4))
}

m <- function(df2, y){              # A Utility function
abs(abs(diff(ncp(df2))) - y)
}

optimize(m, c(1, 1e7), y = .15)[[1]] # Incorrect answer: 1e+07

############# Code Block 2 (with optimize):

f <- function(alpha, q, df1, df2, ncp){      # Objective function
(alpha - suppressWarnings(pf((peta / df1) / ((1 - peta)/df2), df1, df2, ncp, lower.tail = FALSE)))^2
}

ncp <- function(df2){                     # root finding OR optimization
b <- sapply(c(alpha[1], alpha[2]),
function(x) optimize(f, c(0, 1e3), alpha = x, q = peta, df1 = df1, df2 = df2)[[1]])

b / (b + (df2 + 4))
}

m <- function(df2, y){                  # A Utility function
abs(abs(diff(ncp(df2))) - y)
}

optimize(m, c(1, 1e7), y = .15)[[1]]   # Correct answer: 336.3954
``````