Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving integration values in an array

Tags:

r

integration

I want to save the integral values in an array. Say,from q=1 to q=10 in the following program. But due to output with a non-numeric part, I can't do so.

q=10
integrand<-function(x)(q*x^3)
integrate(integrand,lower=0,upper=10)

the output is "25000 with absolute error < 2.8e-10"

How can I remove the non-numeric part?

like image 274
user2458552 Avatar asked Mar 05 '26 09:03

user2458552


1 Answers

str() is your friend to figure this out:

> intval <- integrate(integrand,lower=0,upper=10)
> str(intval)
List of 5
 $ value       : num 25000
 $ abs.error   : num 2.78e-10
 $ subdivisions: int 1
 $ message     : chr "OK"
 $ call        : language integrate(f = integrand, lower = 0, upper = 10)
 - attr(*, "class")= chr "integrate"

So you can see that you need the value element:

> intval$value
[1] 25000

Then:

integrand <- function(x, q=10) { q*x^3 }
tmpfun <- function(q) {
    integrate(integrand,lower=0,upper=10,q=q)$value
}
sapply(1:10,tmpfun)
##  [1]  2500  5000  7500 10000 12500 15000 17500 20000 22500 25000

I hope this is a simplified example, because this particular answer is much more simply obtained by (1) integrating analytically and (2) realizing that a scalar multiple can be taken out of an integral: 1:10*(10^4/4) gets the same answer.

like image 111
Ben Bolker Avatar answered Mar 07 '26 21:03

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!