Numerical integration: Difference between revisions

Content added Content deleted
(categories added)
(→‎{{header|R}}: Somewhat more idiomatic R)
Line 2,648: Line 2,648:


=={{header|R}}==
=={{header|R}}==
{{needs-review|R|These examples may not be idiomatic}}
{{works with|R|2.11.0}}
{{works with|R|2.11.0}}
<lang R>integrate_simpsons <- function(f,a,b,n){
<lang R>integrate.rect <- function(f, a, b, n, k=0) {
#k = 0 for left, 1 for right, 0.5 for midpoint
h = (b-a)/n
sum1 = f(a + h/2)
h <- (b-a)/n
sum2 = 0
x <- seq(a, b, len=n+1)
for (i in 1:(n-1)) {
sum(f(x[-1]-h*(1-k)))*h
sum1 = sum1 + f(a + h * i + h/2)
sum2 = sum2 + f(a + h * i)
}
(h / 6) * (f(a) + f(b) + (4*sum1) + (2*sum2))
}
}


integrate_rect <- function(f,a,b,n,k=0) {
integrate.trapezoid <- function(f, a, b, n) {
h = (b-a)/n
h <- (b-a)/n
x = 0
x <- seq(a, b, len=n+1)
for (i in 1:n) {
fx <- f(x)
x = x + f(a + ((i-k)*h)) * h
sum(fx[-1] + fx[-length(x)])*h/2
}
x
}
}


integrate_trapez <- function(f,a,b,n) {
integrate.simpsons <- function(f, a, b, n) {
h = (b-a)/n
h <- (b-a)/n
x <- seq(a, b, len=n+1)
x=0
for (k in 1:(n-1)) {
fx <- f(x)
x = x + f(a + k*h)
sum(fx[-length(x)] + 4*f(x[-1]-h/2) + fx[-1]) * h/6
}
(h/2) * (f(a) + f(b)) + (h*x)
}
}


Line 2,684: Line 2,675:
f4 <- (function(x) {x})
f4 <- (function(x) {x})


integrate_simpsons(f1,0,1,100) #0.25
integrate.simpsons(f1,0,1,100) #0.25
integrate_simpsons(f2,1,100,1000) # 4.60517
integrate.simpsons(f2,1,100,1000) # 4.60517
integrate_simpsons(f3,0,5000,5000000) # 12500000
integrate.simpsons(f3,0,5000,5000000) # 12500000
integrate_simpsons(f4,0,6000,6000000) # 1.8e+07
integrate.simpsons(f4,0,6000,6000000) # 1.8e+07


integrate_rect(f1,0,1,100,1) #TopLeft 0.245025
integrate.rect(f1,0,1,100,0) #TopLeft 0.245025
integrate_rect(f1,0,1,100,0.5) #Mid 0.2499875
integrate.rect(f1,0,1,100,0.5) #Mid 0.2499875
integrate_rect(f1,0,1,100,0) #TopRight 0.255025
integrate.rect(f1,0,1,100,1) #TopRight 0.255025


integrate_trapez(f1,0,1,100) # 0.250025</lang>
integrate.trapezoid(f1,0,1,100) # 0.250025</lang>


=={{header|REXX}}==
=={{header|REXX}}==