Reputation: 21
I want to make a list of functions and then make a new function that is the product of those functions. For example, I want to make functions (x-4i)^2
, for i=1:50
and then make the product g=prod_i=1^50 (x-4i)^2
. After doing this I want to take the integral of the product function.
To make the list of the functions, I do:
f <- lapply(1:50, function(i){ force(i); function(x) {(x-4i)^2}})
Then I have a list of all functions I want. My problem is how to make the product as a function? I tried many ways but it always leads to "infinite recursion". Could someone please help me?
Upvotes: 2
Views: 126
Reputation: 66844
First of all x-4i
has a special meaning: it becomes a complex number. I suspect you want to use x-4*i
. So,
f <- lapply(1:50, function(i){ force(i); function(x) {(x-4*i)^2}})
To get the product function of these functions you need to evaluate them at the point before multiplying:
fprod <- function(x) prod(sapply(f,function(y) y(x)))
fprod(0)
[1] 1.486445e+189
fprod(1)
[1] 1.394667e+188
To integrate, you will need to use a Vectorize
d function:
integrate(Vectorize(fprod),0,10)
6.328303e+188 with absolute error < 2.1e+181
But note that such large numbers may have accuracy issues.
Upvotes: 1