def gauss_legendre(f,n,a,b):
P=lambda n:1/(2^n*factorial(n))*diff(((x^2-1)^n),x,n)
X=[u.rhs() for u in solve(P(n+1)==0,x)]
scale(t)=(t*(b-a)+a+b)/2
return (b-a)/2*sum([integrate(prod([(x-X[j])/(X[i]-X[j]) for j in [0,..,n] if i!=j]),x,-1,1)*f(scale(X[i])) for i in [0,..,n]])
def newton_cotes(f,n,a,b):
X=lambda i:a+(b-a)/n*i
return sum([integrate(prod([(x-X(j))/(X(i)-X(j)) for j in [0,..,n] if i!=j]),x,a,b)*f(X(i)) for i in [0,..,n]])
f(x)=sin(x); show(f)
l=gauss_legendre(f,4,-1,2).n()
m=newton_cotes(f,4,-1,2).n()
e=f.integrate(x,-1,2).n()
print "legendre:",l,"milne:",m,"exact:",e,"error_legendre:",abs(l-e),"error_milne:",abs(m-e)
|
|
\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \sin\left(x\right)
legendre: 0.956449174395270 milne: 0.955949089353632 exact:
0.956449142415282 error_legendre: 3.19799882131377e-8 error_milne:
0.000500053061650130
\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \sin\left(x\right)
legendre: 0.956449174395270 milne: 0.955949089353632 exact: 0.956449142415282 error_legendre: 3.19799882131377e-8 error_milne: 0.000500053061650130
|