r - Random function not working when used with vectors -
i using r. have made random function (using monte carlo integration) approximates arctan function (equal integral of 1/(1+x^2)). seems work , gives accurate approximations. example 3*arctan(sqrt(3)) should give pi, , below close approximation.
> f=function(x) + {y=runif(10^6,0,x); return(x*mean((1/(1+y^2))))} > f(sqrt(3))*3 [1] 3.140515
however, when use function on sequence of numbers, answers seem come out wrong. below correct values given atan function, f function gives wrong values when used on same vector.
> atan(c(1,1.5,2)) [1] 0.7853982 0.9827937 1.1071487 > f(c(1,1.5,2)) [1] 0.6648275 0.9972412 1.3296550 > f(1) [1] 0.7852855 > f(1.5) [1] 0.9828134 > f(2) [1] 1.107888
notice how when use f on 1, 1.5 , 2 individually, works, not in vector form? what's going on here? have tried running f few times on vector , wrong values pretty consistent 2 decimal places.
using mean()
inside function interferes vectorization. can wrap function in vectorize()
fix it. example
f <- vectorize(function(x) {y=runif(10^6,0,x); return(x*mean((1/(1+y^2))))})
Comments
Post a Comment