[R] integrate

Duncan Murdoch murdoch at stats.uwo.ca
Wed Aug 22 22:05:14 CEST 2007


On 8/22/2007 3:54 PM, Santanu Pramanik wrote:
> Hi,
> I am trying to integrate a function which is approximately constant
> over the range of the integration. The function is as follows:

That's not a function of the input mu.  It includes a random component:

 > my.fcn(10)
[1] 0.9786558
 > my.fcn(10)
[1] 1.022467

You can't expect integrate() to return a sensible answer if you don't 
give it a function that returns consistent results.

Duncan Murdoch

>  
>> my.fcn = function(mu){
> + m = 1000
> + z = 0
> + z.mse = 0
> + for(i in 1:m){
> + z[i] = rnorm(1, mu, 1)
> + z.mse = z.mse + (z[i] - mu)^2
> + }
> + return(z.mse/m)
> + }
> 
>> my.fcn(-10)
> [1] 1.021711
>> my.fcn(10)
> [1] 0.9995235
>> my.fcn(-5)
> [1] 1.012727
>> my.fcn(5)
> [1] 1.033595
>> my.fcn(0)
> [1] 1.106282
>> 
> The function takes the value (approx) 1 over the range of mu. So the
> integration result should be close to 20 if we integrate over (-10, 10).
> But R gives:
> 
>> integrate(my.fcn, -10, 10)
> 685.4941 with absolute error < 7.6e-12
> 
>> integrate(Vectorize(my.fcn), -10, 10)  # this code never terminate
>  
> I have seen in the "?integrate" page it is clearly written:
>  
> If the function is approximately constant (in particular, zero) over
> nearly all its range it is possible that the result and error estimate
> may be seriously wrong. 
>  
> But this doesn't help in solving the problem.
> Thanks,
> Santanu
> 
> 
>  
> JPSM, 1218J Lefrak Hall
> University of Maryland, College Park
> Phone: 301-314-9916
>  
>  
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.



More information about the R-help mailing list