Find the maximum of the function in R

时光总嘲笑我的痴心妄想 提交于 2021-01-27 17:09:44

问题


I have the following function.

Let F(.) is the cumulative distribution function of the gamma distribution with shape = 1 and rate =1. The denominator is the survival function S(X) = 1 - F(X). The g(x) is the mean residual life function.

I wrote the following function in r.

x = 5
denominator = 1 -pgamma(x, 1, 1)
numerator = function(t) (1 - pgamma(t, 1, 1))

intnum  = integrate(numerator , x, Inf)

frac = intnum$value/denominator
frac

How can I find the maximum of the function g(x) for all possible values of X >= 0? Am I able to do this in r? Thank you very much for your help.


回答1:


Before start, i defined the function you maked

surviveFunction<-function(x){
  denominator = 1 -pgamma(x, 1, 1)
  numerator = function(t) (1 - pgamma(t, 1, 1))

  # I used sapply to get even vector x
  intnum  = sapply(x,function(x){integrate(numerator , x, Inf)$value})

  frac = intnum/denominator
  return(frac)
}

Then let's fit our function to function called 'curve' it will draw the plot with continuous data And the result is shown below

df = curve(surviveFunction, from=0, to=45)
plot(df, type='l')

And adjust the xlim to find the maximum value

df = curve(surviveFunction, from=0, to=45,xlim = c(30,40))
plot(df, type='l')

And now we can guess the global maximum is located in near 35

I suggest two options to find the global maximum.

First using the df data to find maximum

> max(df$y,na.rm = TRUE)
 1.054248 #maximum value

> df$x[which(df$y==(max(df$y,na.rm = TRUE)))]
 35.55 #maximum value of x 

Second using the optimize .

> optimize(surviveFunction, interval=c(34, 36), maximum=TRUE)

$maximum
[1] 35.48536

$objective
[1] 1.085282

But the optimize function finds the not the global maximum value i think.

If you see below

optimize(surviveFunction, interval=c(0, 36), maximum=TRUE)

$maximum
[1] 11.11381

$objective
[1] 0.9999887

Above result is not the global maximum i guess it is local maximum.

So, i suggest you using first solution.



来源:https://stackoverflow.com/questions/56639782/find-the-maximum-of-the-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!