What do you call a farm that makes bad jokes?
Corny!
\[ \small{\int_{a}^b f(x)dx \cong \sum_{k=1}^N c_k f(x_k), \,\, c_k = \Delta x = \frac{b-a}{N} } \]
On [-1, 1] with two nodes, GQ uses non-endpoint trapezoid:
\[ \small{ \begin{aligned} c_1 &= c_2 = 1, \, \, x_1 = -\frac{1}{\sqrt{3}}, \, \, x_2 = \frac{1}{\sqrt{3}} \\ \int_{a}^b f(x)dx &\cong \sum_{k=1}^n c_k f(x_k) = 1 \cdot f(x_1) + 1 \cdot f(x_2) \end{aligned} } \]
For this example, \( f(x) = 1.7x^3 + 3x^2 + 2.4x +4 \)
For this example, \( f(x) = 1.7x^3 + 3x^2 + 2.4x +4 \)
For \( n=2 \) data points, want GQ to be exact for polynomials of degree \( 2n-1 = 2(2)-1 = 3 \) or less on [-1,1]:
\[ \small{ \int_{-1}^1 P_3(x)dx = c_1 \cdot P_3(x_1) + 1 \cdot P_3(x_2) } \]
library(pracma)
gaussLegendre(2,-1,1)
$x
[1] -0.5773503 0.5773503
$w
[1] 1 1
library(pracma)
gaussLegendre(3,-1,1)
$x
[1] -7.745967e-01 8.881784e-16 7.745967e-01
$w
[1] 0.5555556 0.8888889 0.5555556
gaussLegendre(2,0,1)
$x
[1] 0.2113249 0.7886751
$w
[1] 0.5 0.5
gaussLegendre(3,1,10)
$x
[1] 2.014315 5.500000 8.985685
$w
[1] 2.5 4.0 2.5
\[ \int_a^b e^{-x^2} dx \]
gaussint <- function(f,x,w) {
y <- f(x)
return (sum(y*w))}
w <- c(1,1)
x <- c(-1/sqrt(3),1/sqrt(3))
f <- function(x){x^2}
gaussint(f,x,w)
[1] 0.6666667
\[ \small{ \int_{a}^b f(x)dx \cong c_1 \cdot f(x_1) + c_2 \cdot f(x_2)} \]
\[ \small{ u = \frac{2x-a-b}{b-a}, \,\, a \leq x \leq b} \]
gaussquad2 <- function(f,a,b) {
w <- c(1,1)
x <- c(-1/sqrt(3),1/sqrt(3))
d <- (b-a)/2
s <- (b+a)/2
u <- d*x + s
y <- f(d*x + s)
return(d*sum(y*w))}
f <- function(x) { x^2 }
G<-gaussquad2(f,0,1)
T<-trap(f,0,1,m = 10)
c(G,T)
[1] 0.3333333 0.3350000
c(abs(1/3-G),abs(1/3-T))
[1] 0.000000000 0.001666667
f <- function(x) { x^4 }
G<-gaussquad2(f,0,1)
T<-trap(f,0,1,m = 10)
c(G,T)
[1] 0.1944444 0.2033300
c(abs(1/5-G),abs(1/5-T))
[1] 0.005555556 0.003330000
gaussquad3 <- function(f,a,b) {
w <- c(5/9,8/9,5/9)
x <- c(-sqrt(3/5),0,sqrt(3/5))
d <- (b-a)/2
s <- (b+a)/2
u <- d*x + s
y <- f(d*x + s)
return(d*sum(y*w))}
f <- function(x) { x^2 }
G<-gaussquad3(f,0,1)
S<-simp(f,0,1,m = 10)
c(G,S)
[1] 0.3333333 0.1133333
c(abs(1/3-G),abs(1/3-S))
[1] 5.551115e-17 2.200000e-01
f <- function(x) { x^4 }
G<-gaussquad3(f,0,1)
S<-simp(f,0,1,m = 10)
c(G,S)
[1] 0.20000000 0.06778083
c(abs(1/5-G),abs(1/5-S))
[1] 0.0000000 0.1322192
f <- function(x){exp(-x^2)}
G<-gaussquad3(f,1,1.5)
S<-simp(f,1,1.5,m = 10)
c(G,S)
[1] 0.1093642 0.3696090
A <- 0.109364260812
c(abs(A-G),abs(A-S))
[1] 6.478000e-08 2.602447e-01