【发布时间】:2014-09-19 03:06:47
【问题描述】:
我正在尝试编写一个 Python 程序来使用 Tanh-sinh 求积来计算:
但是尽管程序在每种情况下都收敛到一个没有错误的合理值,但它并没有收敛到正确的值(对于这个特定的积分是 pi),我找不到问题所在。
程序不要求所需的准确度,而是要求所需的函数评估次数,以便更容易地比较收敛性与更简单的集成方法。评估次数需要是奇数,因为使用的近似值是
谁能建议我做错了什么?
import math
def func(x):
# Function to be integrated, with singular points set = 0
if x == 1 or x == -1 :
return 0
else:
return 1 / math.sqrt(1 - x ** 2)
# Input number of evaluations
N = input("Please enter number of evaluations \n")
if N % 2 == 0:
print "The number of evaluations must be odd"
else:
print "N =", N
# Set step size
h = 2.0 / (N - 1)
print "h =", h
# k ranges from -(N-1)/2 to +(N-1)/2
k = -1 * ((N - 1) / 2.0)
k_max = ((N - 1) / 2.0)
sum = 0
# Loop across integration interval
while k < k_max + 1:
# Compute abscissa
x_k = math.tanh(math.pi * 0.5 * math.sinh(k * h))
# Compute weight
numerator = 0.5 * h * math.pi * math.cosh(k * h)
denominator = math.pow(math.cosh(0.5 * math.pi * math.sinh(k * h)),2)
w_k = numerator / denominator
sum += w_k * func(x_k)
k += 1
print "Integral =", sum
【问题讨论】:
-
在完全不同的情况下,legendre-gauss 正交可能更快(使用来自pomax.github.io/bezierinfo/legendre-gauss.html 的表格数据或其他高精度)
-
收敛到什么价值?
-
您应该将奇异点更改为 x= 1。由于四舍五入,您不会落在整数值上。
标签: python python-2.7 numerical-integration