Re: [R] Numerical Integration in 1D

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Fri, 07 Mar 2008 20:40:10 +0000 (GMT)

On Fri, 7 Mar 2008, Max wrote:

> Prof Brian Ripley formulated on Friday :
>> On Fri, 7 Mar 2008, Max wrote:
>>
>>> Dear UseRs,
>>>
>>> I'm curious about the derivative of n!.
>>>
>>> We know that Gamma(n+1)=n! So when on takes the derivative of
>>> Gamma(n+1) we get Int(ln(x)*exp(-x)*x^n,x=0..Inf).
>>>
>>> I've tried code like
>>>
>>>> integrand<-function(x) {log(x)*exp(x)*x^n}
>>>> integrate(integrand,lower=0,upper=Inf)
>>>
>>> It seems that R doesn't like to integrate for any n, and I was
>>> wondering if anyone knew a way around this?
>>
>> ln(x) e^x x^n is not integrable on (0, Inf). You presumably slipped over
>> a minus sign, but your definition of gamma(n) is wrong -- see ?gamma.
>>
>> integrate(function(x) exp(-x)*x^n, lower=0, upper=Inf)
>>
>> will work for gamma(n+1).
>
> I did miss a minus sign in the integration, which explains part of my
> problems. The function of interest is the derivative of Gamma(n+1) with
> respect to n, but obviously integrated over x from 0 to Infinity.

And you said n!, so n must be integer and you cannot differentiate a function of a integer argument.

If you are interested in the derivative of gamma(x), check out ?digamma.

> What happens now is:
>
>> integrand<-function(x) {log(x)*exp(-x)*x^n}
>> integrate(integrand,lower=0,upper=Inf)
> Error in f(x, ...) : object "n" not found
>
> Any ideas on how to get around this error?

Set 'n' in the evaluation environment.

E.g.

> n <- 3
> integrate(integrand, lower=0, upper=Inf)
7.536706 with absolute error < 4.7e-06
> digamma(4)*gamma(4)

[1] 7.536706

-- 
Brian D. Ripley,                  ripley_at_stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 07 Mar 2008 - 20:43:45 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 07 Mar 2008 - 21:30:19 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive