Simpson's rule in Python

前端 未结 6 2233
悲&欢浪女
悲&欢浪女 2021-01-06 00:43

For a numerical methods class, I need to write a program to evaluate a definite integral with Simpson\'s composite rule. I already got this far (see below), but my answer is

6条回答
  •  清歌不尽
    2021-01-06 01:05

    def simps(f, a, b, N):   # N must be an odd integer
        """ define simpson method, a and b are the lower and upper limits of
        the interval, N is number of points, dx is the slice
            """
        integ = 0
        dx = float((b - a) / N)
    
        for i in range(1,N-1,2):
            integ += f((a+(i-1)*dx)) + 4*f((a+i*dx)) + f((a+(i+1)*dx))
            integral = dx/3.0 * integ
        
        # if number of points is even, then error araise
        if (N % 2) == 0:
          raise ValueError("N must be an odd integer.")
            
    
        return integral
    
    
    def f(x):
        return x**2
    
    
    integrate = simps(f,0,1,99)
    print(integrate)
    

提交回复
热议问题