首页 > 解决方案 > 如何在 epsilon=1e-8 上迭代 for 循环以实现 Simpson 的积分器

问题描述

我已经实现了以下逻辑,并针对不同的问题(数组范围)提出了这个问题。我得到了输出,但它没有通过 for 循环进行迭代,因为我已经给出了frange(start, stop, range)

解释

"""Approximate definite integral of function from a to b using Simpson's method.
This function is vectorized, it uses numpy array operations to calculate the approximation.
This is an adaptive implementation, the method starts out with N=2 intervals, and try
successive sizes of N (by doubling the size), until the desired precision, is reached.
This adaptive solution uses our improved approach/equation for Simpson's method, to 
avoid unnecessary recalculations of the integrand function.

a, b - Scalar float values, the begin, and endpoints of the interval we are to
        integrate the function over.
f - A vectorized function, should accept a numpy array of x values, and compute the
      corresponding y values for all points according to some function.
epsilon - The desired precision to calculate the integral to.  Default is 8 decimal places
      of precision (1e-8)

returns - A tuple, (ival, error).  A scalar float value, the approximated integral of 
       the function over the given interval, and a scaler float value of the 
       approximation error on the integral
"""

代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
import pylab as pl
def simpsons_adaptive_approximation(a, b, f, epsilon=1e-8):

    N_prev = 2 # the previous number of slices
    h_prev = (b - a) / N_prev # previous interval width
    x = np.arange(a+h_prev, b, h_prev) # x locations of the previous interval
    I_prev =  h_prev * (0.5 * f(a) + 0.5 * f(b) + np.sum(f(x)))

    # set up variables to adaptively iterate successively better approximations
    N_cur  = 2 # the current number of slices
    I_cur  = 0.0 # calculated in loop iteration
    error  = 1.0 # calculated in loop iteration
    itr    = 1 # keep track of the number of iterations we perform, for display/debug

    h = (b-a)/float(epsilon)
    I_cur = f(a) + f(b)

    while error > epsilon:
        for i in pl.frange(1,epsilon,1):
            print('Hello')
            if(i%2 ==0):
                print('Hello')
                I_cur = I_cur + (2*(f(a + i*h)))
            else:
                I_cur = I_cur + (4*(f(a + i*h)))

        error = np.abs((1.0/3.0) * (I_cur - I_prev))
        print("At iteration %d (N=%d), val=%0.16f prev=%0.16f error=%e" % (itr, N_cur, I_cur, I_prev, error) )
        I_cur *= (h/3.0)

        I_prev = I_cur
        N_prev = N_cur
        N_cur *= 2
        itr += 1

    return (I_cur, error)

调用上述函数的另一个函数

def f2(x):
    return x**4 - 2*x + 1

a = 0.0
b = 2.0
eps = 1e-10
(val, err) = simpsons_adaptive_approximation(a, b, f2, eps)
print( "Calculated value: %0.16f  error: %e  for an epsilon of: %e" % (val, err, eps) ) 

以下是结果

At iteration 1 (N=2), val=14.0000000000000000 prev=7.0000000000000000 error=2.333333e+00
At iteration 2 (N=4), val=93333333333.3333435058593750 prev=93333333333.3333435058593750 error=0.000000e+00
Calculated value: 622222222222222295040.0000000000000000  error: 0.000000e+00  for an epsilon of: 1.000000e-10

它应该给我更多的迭代

任何人都可以帮助我迭代 for 循环以获得更多结果

标签: pythonpython-3.xsimpsons-rule

解决方案


推荐阅读