Simpson's rule in Python

前端 未结 6 2044
悲&欢浪女
悲&欢浪女 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 00:57

    Example of implementing Simpson's rule for integral sinX with a = 0 and b = pi/4. And use 10 panels for the integration

    def simpson(f, a, b, n):
      x = np.linspace(a, b, n+1)
      w = 2*np.ones(n+1); w[0] = 1.0; w[-1] = 1;
      for i in range(len(w)):
          if i % 2 == 1:
              w[i] = 4
      width = x[1] - x[0]
      area = 0.333 * width * np.sum( w*f(x))
      return area
    
    f = lambda x: np.sin(x)
    a = 0.0; b = np.pi/4
    
    areaSim = simpson(f, a, b, 10)
    print(areaSim)
    

提交回复
热议问题