Simpson's rule in Python

前端 未结 6 2064
悲&欢浪女
悲&欢浪女 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

    You probably forget to initialize x before the second loop, also, starting conditions and number of iterations are off. Here is the correct way:

    def simpson(f, a, b, n):
        h=(b-a)/n
        k=0.0
        x=a + h
        for i in range(1,n/2 + 1):
            k += 4*f(x)
            x += 2*h
    
        x = a + 2*h
        for i in range(1,n/2):
            k += 2*f(x)
            x += 2*h
        return (h/3)*(f(a)+f(b)+k)
    

    Your mistakes are connected with the notion of a loop invariant. Not to get into details too much, it's generally easier to understand and debug cycles which advance at the end of a cycle, not at the beginning, here I moved the x += 2 * h line to the end, which made it easy to verify where the summation starts. In your implementation it would be necessary to assign a weird x = a - h for the first loop only to add 2 * h to it as the first line in the loop.

提交回复
热议问题