高斯(-Legendre)在python中的正交

问题描述 投票:0回答:4

我正在尝试使用高斯求积来近似函数的积分。 (更多信息: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

这些是相应的错误消息

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
python numpy integration gaussian
4个回答
3
投票

正如威尔所说,你在数组和函数之间感到困惑。

您需要单独定义要集成的功能并将其传递给高斯。

EG

def my_f(x):
    return 2*x**2 - 3*x +15 

gauss(m_f,2,1,-1)

你也不需要循环,因为numpy数组是vectorized对象。

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

0
投票

gauss1(f,n)中,你正在将f视为一个函数,就像它是一个数组一样,因为你正在重新分配它;

def gauss1(f,n):
  [x,w] = p_roots(n+1)
  f = (1-x**2)**0.5 # This line is your problem.
  for i in range(n+1):
    G = sum(w[i]*f(x[i]))
  return G

你在第二个函数中做了类似的事情。


0
投票

我的一个小项目quadpy可能会有所帮助:

import numpy
import quadpy


def f(x):
    return numpy.exp(x)

scheme = quadpy.line_segment.GaussRadau(10)
val = quadpy.line_segment.integrate(f, 0.0, 1.0, scheme)

print(val)

1D还有许多其他的正交方案。


0
投票

示例:使用高斯积分求解n = 2的积分2 + sinX,其中b = pi / 2且a = 0

import numpy as np

E = np.array([-0.774597, 0.000000, 0.774597])
A = np.array([0.555556, 0.888889, 0.555556])

def gauss(f, a, b, E, A):
    x = np.zeros(3)
    for i in range(3):
        x[i] = (b+a)/2 + (b-a)/2 *E[i]

    return (b-a)/2 * (A[0]*f(x[0]) + A[1]*f(x[1]) + A[2]*f(x[2]))


f = lambda x: 2 + np.sin(x)
a = 0.0; b = np.pi/2

areaGau = gauss(f, a, b, E, A)
print("Gaussian integral: ", areaGau)
© www.soinside.com 2019 - 2024. All rights reserved.