Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple integration

Tags:

r

 constant <- function(x){1}

 integrate(constant,lower=1,upper=10)

this is probably more than ridiculously simple, but any reason as to why this isn't working?

is there a different way I should be writing the function for constants?

like image 482
Doug Avatar asked Dec 18 '25 13:12

Doug


2 Answers

You can use the Vectorize function to convert a non-vectorized function into the sort of function that integrate requires:

> constant <- function(x){1}
> Vconst <- Vectorize(constant)
>  integrate(Vconst,lower=1,upper=10)
9 with absolute error < 1e-13
like image 121
IRTFM Avatar answered Dec 21 '25 05:12

IRTFM


From ?integrate:

An R function taking a numeric first argument and returning a numeric vector of the same length. Returning a non-finite element will generate an error.

You need to return a vector the same length as x. Try:

constant <- function(x){rep(1,length(x))}
like image 23
Alex Brown Avatar answered Dec 21 '25 06:12

Alex Brown