[R] Numerical Integration

Julio Rojas jcredberry at ymail.com
Fri Dec 18 16:02:28 CET 2009


Dear @ll. I have to calculate numerical integrals for triangular and trapezoidal figures. I know you can calculate the exactly, but I want to do it this way to learn how to proceed with more complicated shapes. The code I'm using is the following:

integrand<-function(x) {
   print(x)
   if(x<fx[1]) return(0)
   if(x>=fx[1] && x<fx[2]) return((x-fx[1])/(fx[2]-fx[1]))
   if(x>fx[2] && x<=fx[3]) return(1)
   if(x>fx[3] && x<=fx[4]) return((x-fx[4])/(fx[3]-fx[4]))
   if(x>fx[4]) return(0)

 }

fx<-data[i,j,]
reltol<-1e-07
integrate(Vectorize(integrand),0,1,rel.tol=reltol,subdivisions=200)$value

It works for most cases, but then, I tried for the triangle fx<-[0.3,0.5,0.5,0.6] and the following error was presented:

> integrate(Vectorize(integrand),0,1,rel.tol=reltol,subdivisions=200)
[1] 0.5
[1] 0.01304674
[1] 0.9869533
[1] 0.06746832
[1] 0.9325317
[1] 0.1602952
[1] 0.8397048
[1] 0.2833023
[1] 0.7166977
[1] 0.4255628
[1] 0.5744372
[1] 0.002171418
[1] 0.9978286
[1] 0.03492125
[1] 0.9650787
[1] 0.1095911
[1] 0.8904089
[1] 0.2186214
[1] 0.7813786
[1] 0.3528036
[1] 0.6471964
Error in integrate(Vectorize(integrand), 0, 1, rel.tol = reltol,
subdivisions = 200) :
 evaluation of function gave a result of wrong type

Does anybody know what happened? Thanks in advance!!!


      ____________________________________________________________________________________
¡Obtén la mejor experiencia en la web!
Descarga gratis el nuevo Internet Explorer 8. 
http://downloads.yahoo.com/ieak8/?l=e1




More information about the R-help mailing list