Numerical integration: Difference between revisions

m
→‎{{header|R}}: simpler and more general
(Numerical integration in Yabasic)
m (→‎{{header|R}}: simpler and more general)
Line 4,547:
{{works with|R|2.11.0}}
 
TheseThe presumeinteg function defined below uses arbitrary abscissae and weights passed as argument (resp. u and v). It assumes that f can take a vector argument.
 
<lang Rrsplus>integrate.rectinteg <- function(f, a, b, n, k=0u, v) {
h <- (b - a) / n
#k = 0 for left, 1 for right, 0.5 for midpoint
hs <- (b-a)/n0
xfor <-(i in seq(a0, b, len=n+ - 1)) {
s <- s + sum(v * f(x[-1]-a + i * h + u *(1-k h)))*h
}
s * h
}
 
integrate.trapezoidtest <- function(f, a, b, n) {
c(rect.left = integ(f, a, b, n, 0, 1),
h <- (b-a)/n
x <- seqrect.right = integ(f, a, b, len=n+, 1, 1),
rect.mid = integ(f, a, b, n, 0.5, 1),
fx <- f(x)
trapezoidal = integ(f, a, b, n, c(0, 1), c(0.5, 0.5)),
sum(fx[-1] + fx[-length(x)])*h/2
simpson = integ(f, a, b, n, c(0, 0.5, 1), c(1, 4, 1) / 6))
}
 
test(\(x) x^3, 0, 1, 100)
integrate.simpsons <- function(f, a, b, n) {
# rect.left rect.right rect.mid trapezoidal simpson
h <- (b-a)/n
# 0.2450250 0.2550250 0.2499875 0.2500250 0.2500000
x <- seq(a, b, len=n+1)
fx <- f(x)
sum(fx[-length(x)] + 4*f(x[-1]-h/2) + fx[-1]) * h/6
}
 
f1 <- (function(x) {x^3})
f2 <- (function(x) {1/x})
f3 <- (function(x) {x})
f4 <- (function(x) {x})
 
test(\(x) 1 / x, 1, 100, 1000)
integrate.simpsons(f1,0,1,100) #0.25
# rect.left rect.right rect.mid trapezoidal simpson
integrate.simpsons(f2,1,100,1000) # 4.60517
# 4.654991 4.556981 4.604763 4.605986 4.605170
integrate.simpsons(f3,0,5000,5000000) # 12500000
integrate.simpsons(f4,0,6000,6000000) # 1.8e+07
 
test(\(x) x, 0, 5000, 5e6)
integrate.rect(f1,0,1,100,0) #TopLeft 0.245025
# rect.left rect.right rect.mid trapezoidal simpson
integrate.rect(f1,0,1,100,0.5) #Mid 0.2499875
# 12499998 12500003 12500000 12500000 12500000
integrate.rect(f1,0,1,100,1) #TopRight 0.255025
 
test(\(x) x, 0, 6000, 6e6)
integrate.trapezoid(f1,0,1,100) # 0.250025</lang>
# rect.left rect.right rect.mid trapezoidal simpson
# 1.8e+07 1.8e+07 1.8e+07 1.8e+07 1.8e+07</lang>
 
=={{header|Racket}}==
1,336

edits