Find a variable value for a --- Target function

Asked

Viewed 203 times

3

good afternoon staff

I have a function that I know the result, and I want to find the value of parameter c for each result I have , similar to Excel target function

#Vetor com valores de cv para cada parcela
cv<-c(0.2901,0.2836,0.3150,0.2535,0.2762,0.2578,0.2729,0.2737,0.2943,0.2243)

# Função para estimar c ---------------------------------------------------
cvcalculado<-function(c){
sqrt((exp(log(gamma(1+(2/c)))))-(exp(log(gamma(1+ 
(1/c))))^2))/(exp(log(gamma(1+(1/c)))))

}

I need to get the value of the parameter c for each vector value cv, where the vector values cv are the function response given any value of c

So I’ll have an estimate of c for each vector value cv

I have tried to go down this road, but no answer is given for each value of cv, but a global response

 optimise(cvcalculado, cv)

thank you in advance

  • 3

    The problem is poorly defined. First, the function is monotonous decreasing, there is nothing to optimize, see curve(cvcalculado, 1, 100). Secondly, the value of c for which cvcalculado(c) == cv[1] and then the value of c for which cvcalculado(c) == cv[2], etc.?

  • exactly, sorry for the poor elaboration of the problem

  • Done, see my answer.

1 answer

6


To calculate the values of c that are solution of the equations cvcalculado(c) == cv, for each value of cv, I will first define another function, the auxiliary function f. This serves to transform the problem into finding the solutions of cvcalculado - cv == 0. This is required to use the base R function uniroot.

Note also that instead of log(gamma(.)) used lgamma(.).

cvcalculado <- function(c){
  sqrt(exp(lgamma(1 + 2/c)) - exp(lgamma(1 + 1/c))^2) /
    exp(lgamma(1 + 1/c))
}

f <- function(x, CV) cvcalculado(x) - CV

To calculate the roots of the function f with the value cv[1] this is how it is done:

uniroot(f, interval = c(0.1, 10), CV = cv[1])
#$root
#[1] 3.854489
#
#$f.root
#[1] -1.55541e-06
#
#$iter
#[1] 8
#
#$init.it
#[1] NA
#
#$estim.prec
#[1] 6.103516e-05

The solution is 3.854489.

Now just apply (lapply) this way to get roots to the whole vector cv.

res <- lapply(cv, function(.CV)
  uniroot(f, interval = c(0.1, 10), CV = .CV))

param.vec <- sapply(res, '[[', 'root')

param.vec
# [1] 3.854489 3.952367 3.517988 4.473290 4.069609 4.391188 4.124002
# [8] 4.110691 3.793610 5.116052

Browser other questions tagged

You are not signed in. Login or sign up in order to post.