I'm trying to use Gaussian quadrature to approximate the integral of a function. (More info here: http://austingwalters.com/gaussian-quadrature/). The first function is on the interval [-1,1]. The second function is generalized to [a,b] by change of variable. The problem is that I keep getting the error "'numpy.ndarray' object is not callable". I assume (please correct me if I'm wrong) this means I've tried to call the arrays w and x as functions, but I'm not sure how to fix this.
This is the code
from __future__ import division
from pylab import *
from scipy.special.orthogonal import p_roots
def gauss1(f,n):
[x,w] = p_roots(n+1)
f = (1-x**2)**0.5
for i in range(n+1):
G = sum(w[i]*f(x[i]))
return G
def gauss(f,a,b,n):
[x,w] = p_roots(n+1)
f = (1-x**2)**0.5
for i in range(n+1):
G = 0.5*(b-a)*sum(w[i]*f(0.5*(b-a)*x[i]+ 0.5*(b+a)))
return G
These are the respective error messages
gauss1(f,4)
Traceback (most recent call last):
File "<ipython-input-82-43c8ecf7334a>", line 1, in <module>
gauss1(f,4)
File "C:/Users/Me/Desktop/hw8.py", line 16, in gauss1
G = sum(w[i]*f(x[i]))
TypeError: 'numpy.ndarray' object is not callable
gauss(f,0,1,4)
Traceback (most recent call last):
File "<ipython-input-83-5603d51e9206>", line 1, in <module>
gauss(f,0,1,4)
File "C:/Users/Me/Desktop/hw8.py", line 23, in gauss
G = 0.5*(b-a)*sum(w[i]*f(0.5*(b-a)*x[i]+ 0.5*(b+a)))
TypeError: 'numpy.ndarray' object is not callable
In numerical analysis, Gauss–Legendre quadrature is a form of Gaussian quadrature for approximating the definite integral of a function.
The Legendre-Gauss quadrature formula is a special case of Gaussian quadratures which allow efficient approximation of a function with known asymptotic behavior at the edges of the interval of integration.
The Gaussian quadrature method is an approximate method of calculation of a certain integral . By replacing the variables x = (b – a)t/2 + (a + b)t/2, f(t) = (b – a)y(x)/2 the desired integral is reduced to the form .
The points used in Gaussian Quadrature are the roots of Pn+1, {x0,x1,...,xn}. Because of the properties of the Legendre polynomials, it turns out that if P(x) is any poly- nomial of degree k up to 2n + 1, then the Gaussian Quadrature estimate of the integral of P(x) is exact.
As Will says you're getting confused between arrays and functions.
You need to define the function you want to integrate separately and pass it into gauss.
E.g.
def my_f(x):
return 2*x**2 - 3*x +15
gauss(m_f,2,1,-1)
You also don't need to loop as numpy arrays are vectorized objects.
def gauss1(f,n):
[x,w] = p_roots(n+1)
G=sum(w*f(x))
return G
def gauss(f,n,a,b):
[x,w] = p_roots(n+1)
G=0.5*(b-a)*sum(w*f(0.5*(b-a)*x+0.5*(b+a)))
return G
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With