Reputation:
evaluating an integral depending on two parameters
A <- 0.0004
B <- 0.0013
c <- 1.0780
f1 <- function(x) {
f2 <- function(s) {
A + B * c^(x+s)
}
return(f2)
}
tpx <- function(t,x) {
exp(-integrate(f1(x), lower=0, upper=t)$value)
}
i get
> tpx(1,1)
[1] 0.9981463
for the ordered pair (1,1). when using the colon operator
> tpx(1,1:2)
[1] 0.9980945
Warning messages:
1: In x + s :
longer object length is not a multiple of shorter object length
2: In x + s :
longer object length is not a multiple of shorter object length
3: In x + s :
some error messages occur. is it possible to adjust the integration variable s
? what causes the output right before the warning messages? it is neither
> tpx(1,1)
[1] 0.9981463
nor
> tpx(1,2)
[1] 0.998033
i suppose i get something wrong :S
Upvotes: 0
Views: 57
Reputation: 21507
You can use the following
sapply(1:2, tpx, t = 1)
Why?
The error is caused because: integrate expects f to be (quote 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.
But
> s = 1
> A + B * c^(1:2+s)
[1] 0.001910709 0.002028545
is of length 2 whereas s is of length 1.
sapply
supplies one elements at a time the f1
and combines the result afterwards. That's why it works.
Comment:
You can also simplify your f1
, f2
and tpx
function as follows:
f1 <- function(s, x, A, B, c){
A + B * c^(x+s)
}
tpx <- function(x,t){
exp(-integrate(f1, lower=0, upper=t, x, A, B, c)$value)
}
Again quoting from ?integrate
... - additional arguments to be passed to f.
Meaning that the parameter x, A, B, c
will be passed to f1
and only the first argument will be used by the integration.
Upvotes: 1