在Python中集成

时间:2017-02-10 03:08:17

标签: python

我一直想集成在python中,但我不使用Scipy,Numpy,或者没有任何其他程序可以集成到python中。在编码方面,我几乎是一个新手,但我需要帮助整合。我复制了一个小代码,但我仍需要改进它。

def LeftEndSum(startingx, endingx, numberofRectangles) :

    width = (float(endingx) - float(startingx)) / numberofRectangles

    runningSum = 0

    for i in range(numberofRectangles) :
        height = f(startingx + i*width)
        area = height * width
        runningSum += area
    return runningSum

我正在尝试集成,但我想获得一个数据点列表,然后我可以在集成结束时绘制成图表

我有一个定义区间[a,b]和delta n =(点之间#框的变化)的想法,在那里我可以进行收敛测试以阻止循环获得点。收敛测试将会进行。

如果I(n(旧值)+ delta(n)) - I(n(旧值))/ I(n(旧))<小量 其中epsilon = 1x10 ^ -6

其中如果代码中断的集成值

2 个答案:

答案 0 :(得分:2)

假设你想要将y = x * x从0.0到10.0整合,我们知道答案是333.33333。以下是一些代码:

def y_equals_x_squared(x):
    y = x*x
    return y

def LeftEndSum(startingx, endingx, numberofRectangles) :
    width = (float(endingx) - float(startingx)) / numberofRectangles
    #print "width = " + str(width)
    runningSum = 0
    i = 1
    while i <= numberofRectangles:
        x = (endingx - startingx)/(numberofRectangles) * (i - 1) + startingx
        height = y_equals_x_squared(x)
        area = height * width
        #print "i, x , height, area = " + str(i) + ", " + str(x) + ", " + str(height) + ", " + str(area)
        runningSum += area
        i += 1
    return runningSum
#-----------------------------------------------------------------------------
startingx = 0.0 
endingx = 10.0 
#
numberofRectangles = 3
old_answer = LeftEndSum(startingx, endingx, numberofRectangles)
#
numberofRectangles = 4
new_answer = LeftEndSum(startingx, endingx, numberofRectangles)
#
delta_answer = abs(new_answer - old_answer)
#
tolerance = 0.0001
max_iterations = 500
iteration_count = 0
iterations = []
answers = []
while delta_answer > tolerance:
    numberofRectangles += 100
    new_answer = LeftEndSum(startingx, endingx, numberofRectangles)
    delta_answer = abs(new_answer - old_answer)
    old_answer = new_answer
    iteration_count += 1
    iterations.append(iteration_count)
    answers.append(new_answer)
    print "iteration_count, new_answer = " + str(iteration_count) + ", " + str(new_answer)
    if(iteration_count > max_iterations):
        print "reached max_iterations, breaking"
        break
#
OutputFile = "Integration_Results.txt"
with open(OutputFile, 'a') as the_file:
    for index in range(len(answers)):
        the_file.write(str(index) + " " + str(answers[index]) + "\n")
#
import matplotlib.pyplot as plt
#
fig, ax = plt.subplots()
ax.plot(iterations, answers, 'r-', label = "Increasing # Rectangles")
title_temp = "Simple Integration"
plt.title(title_temp, fontsize=12, fontweight='bold', color='green')
ax.legend(loc='best', ncol=1, fancybox=True, shadow=True)
plt.xlabel('Number of Iterations')
plt.ylabel('Answer') 
ax.grid(True)
plt.show(block=True)

请注意,我们在最后绘制了答案与迭代次数,并且随着迭代次数的增加,它会非常缓慢地接近实际答案。还有其他集成方法比简单的矩形(例如梯形法则)更好。当您放入while循环并检查容差时,请务必进行max_iterations检查,以免陷入无限循环。

您可以在此处查看答案: http://www.integral-calculator.com/ 我们如何知道答案是333.3333

答案 1 :(得分:1)

sum作为参数包含在函数中更有意义。为什么硬连线固定的配方?此外,通过使用应用于生成器的内置函数def riemannSum(f,a,b,n,sample = 'L'): """computes Riemann sum of f over [a,b] using n rectangles and left ('L'), right ('R') or midpoints ('M')""" h = (b-a)/float(n) if sample.upper() == 'L': s = a #s = first sample point elif sample.upper() == 'R': s = a + h else: s = a + h/2.0 return h*sum(f(s+i*h) for i in range(n)) ,可以大大简化代码:

>>> def reciprocal(x): return 1/x

>>> riemannSum(reciprocal,1,2,100)
0.6956534304818242

您可以明确定义函数然后集成它们:

>>> riemannSum(lambda x: x**2,0,1,100,'m')
0.333325

(确切的值是2的自然对数,约为0.693147)

或者,您可以使用匿名函数(lambda表达式):

math

或者,您可以使用>>> riemannSum(math.sin,0,math.pi,10) 1.9835235375094546 模块中已有的功能:

def simpsonsRule(f,a,b,n):
    if n%2 == 1:
        return "Not applicable"
    else:
        h = (b-a)/float(n)
        s = f(a) + sum((4 if i%2 == 1 else 2)*f(a+i*h) for i in range(1,n)) + f(b)
        return s*h/3.0

这些方法都不是很准确。更精确的是Simpson's Rule,这在Python中也很容易做到:

>>> simpsonsRule(math.sin,0,math.pi,10)
2.0001095173150043

例如:

var n = 14;
n.toString();

这比具有10个矩形的黎曼和更准确(真值为2)。