numpy中高斯 - 勒让德正交的不同区间

时间:2015-10-31 23:59:10

标签: python numpy scipy numerical-integration

我们如何在[-1, 1]以外的时间间隔内使用NumPy包numpy.polynomial.legendre.leggauss

以下示例在[-1, 1]间隔内将scipy.integrate.quad与Gauss-Legendre方法进行比较。

import numpy as np
from scipy import integrate

# Define function and interval
a = -1.
b =  1.
f = lambda x: np.cos(x)

# Gauss-Legendre (default interval is [-1, 1])
deg = 6
x, w = np.polynomial.legendre.leggauss(deg)
gauss = sum(w * f(x))

# For comparison
quad, quad_err = integrate.quad(f, a, b)

print 'The QUADPACK solution: {0:.12} with error: {1:.12}'.format(quad, quad_err)
print 'Gauss-Legendre solution: {0:.12}'.format(gauss)
print 'Difference between QUADPACK and Gauss-Legendre: ', abs(gauss - quad)

输出:

The QUADPACK solution: 1.68294196962 with error: 1.86844092378e-14
Gauss-Legendre solution: 1.68294196961
Difference between QUADPACK and Gauss-Legendre:  1.51301193796e-12

2 个答案:

答案 0 :(得分:6)

change the interval,使用比如

将x值从[-1,1]转换为[a,b]
gauss = sum(w * f(t)) * 0.5*(b - a)

然后将正交公式缩放为(b-a)/ 2:

import numpy as np
from scipy import integrate

# Define function and interval
a = 0.0
b = np.pi/2
f = lambda x: np.cos(x)

# Gauss-Legendre (default interval is [-1, 1])
deg = 6
x, w = np.polynomial.legendre.leggauss(deg)
# Translate x values from the interval [-1, 1] to [a, b]
t = 0.5*(x + 1)*(b - a) + a
gauss = sum(w * f(t)) * 0.5*(b - a)

# For comparison
quad, quad_err = integrate.quad(f, a, b)

print 'The QUADPACK solution: {0:.12} with error: {1:.12}'.format(quad, quad_err)
print 'Gauss-Legendre solution: {0:.12}'.format(gauss)
print 'Difference between QUADPACK and Gauss-Legendre: ', abs(gauss - quad)

以下是您示例的修改版本:

var date = new Date();

var str = ["Sunday", "mon", "tues", "wed", "thurs", "fri", "sat", "sun"][date.getDay()];
str += ", " + ["jan", "feb", "mar", "apr", "may", "june", "jul", "aug", "sep", "oct", "November", "dec"][date.getMonth()];
str += " "  + date.getDate();
str += ", " + date.getFullYear();

console.log(str);

打印:

The QUADPACK solution: 1.0 with error: 1.11022302463e-14
Gauss-Legendre solution: 1.0
Difference between QUADPACK and Gauss-Legendre:  4.62963001269e-14

答案 1 :(得分:0)

quadpy(我的一个小项目)作为一个更简单的语法:

import numpy
import quadpy

out = quadpy.line_segment.integrate(
    numpy.cos,
    [1.1, 1.2],  # the interval
    quadpy.line_segment.GaussLegendre(4)
    )