new*_*ser 5 python numpy gaussian numerical-integration
我正在尝试使用高斯求积来近似函数的积分。(更多信息在这里:http : //austingwalters.com/gaussian-quadrature/)。第一个函数在区间 [-1,1] 上。第二个函数通过变量的变化推广到 [a,b]。问题是我不断收到错误“'numpy.ndarray' 对象不可调用”。我假设(如果我错了,请纠正我)这意味着我试图将数组 w 和 x 称为函数,但我不确定如何解决这个问题。
这是代码
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
Run Code Online (Sandbox Code Playgroud)
这些是各自的错误消息
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
Run Code Online (Sandbox Code Playgroud)
小智 5
正如威尔所说,你对数组和函数感到困惑。
您需要单独定义要积分的函数并将其传递给高斯。
例如
def my_f(x):
return 2*x**2 - 3*x +15
gauss(m_f,2,1,-1)
Run Code Online (Sandbox Code Playgroud)
您也不需要循环,因为 numpy 数组是矢量化对象。
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
Run Code Online (Sandbox Code Playgroud)