Numerical integration: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: fix float type per language change)
Line 2,159:
s2 = sum( f(a+i*h) for i in range(1,steps))
return (h/6.0)*(f(a)+f(b)+4.0*s1+2.0*s2)</lang>
 
=={{header|R}}==
{{needs-review|R|These examples may not be idiomatic}}
{{works with|R|2.11.0}}
<lang R>integrate_simpsons <- function(f,a,b,n){
h = (b-a)/n
sum1 = f(a + h/2)
sum2 = 0
for (i in 1:(n-1)) {
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) {
h = (b-a)/n
x = 0
for (i in 1:n) {
x = x + f((a + (i-k)) * h )
}
x
}
 
integrate_trapez <- function(f,a,b,n) {
h = (b-a)/n
x=0
for (k in 1:(n-1)) {
x = x + f(a + k*h)
}
(h/2) * (f(a) + f(b)) + (h*x)
}
 
f1 <- (function(x) {x^3})
f2 <- (function(x) {1/x})
f3 <- (function(x) {x})
f4 <- (function(x) {x})
 
integrate_simpsons(f1,0,1,100) #25
integrate_simpsons(f2,1,100,1000) # 4.60517
integrate_simpsons(f3,0,5000,5000000) # 12500000
integrate_simpsons(f4,0,6000,6000000) # 1.8e+07
 
integrate_rect(f1,0,1,100,1) #TopLeft 24.5025
integrate_rect(f1,0,1,100,0.5) #Mid 24.99875
integrate_rect(f1,0,1,100,0) #TopRight 25.5025
 
integrate_trapez(f1,0,1,100) # 0.250025</lang>
 
=={{header|REXX}}==