Reputation: 265
I have built a function in R, which calculates the value of the density phi of the standard normal. Here it is:
f<-function(x){
v<-1/sqrt(2*pi)*exp(-0.5*x**2)
return (v)
}
then, I built a sequence of values, and I applied the function f to each of this value:
x<-seq(-10,10,length=100)
f(x)
plot(f(x),t="l")
Now, I want to demonstrate that the maximum of this function is in 0; how can I do, using the function nlm
?
Upvotes: 1
Views: 413
Reputation: 545588
As you probably know from reading the documentation, nlm
performs minimisation, not maximisation. So you’ll need to wrap it to invert your function’s sign:
nlmax = function (f, p, ...) {
res = nlm(function(x, ...) -f(x, ...), p, ...)
res$maximum = -res$minimum
res$minimum = NULL
res
}
Note how we’re inverting two things:
f
when invoking nlm
minimum
.And now you can run it on your function:
nlmax(f, 1)
Upvotes: 2