简体   繁体   中英

Numerical method in python- can't spot the problem?

I am writing this numerical method formula of trapezium rule for double integrals. 在此处输入图片说明

Note that hx = (ba)/nx, hy = (dc)/ny to get the interval widths and xj = a+hx j and yi = c+hy i

A few problems in your code:

First yes your indentation here is off (but I assume it's from not copying it across well since this would lead to an error rather than a wrong value). In the future make sure the indentation in your question corresponds to what you have at on your own computer before posting...

Then a term should be added within a for if and only if it's in the corresponding sum... Here you put everything within the double for loop which corresponds to having all the terms in the double sum.

Finally range(1,n) already stops at n-1 only so you want to remove those -1 in the ranges.

In the end:

def double_integral(f,a,b,c,d,nx,ny):

    hx = (b-a)/nx
    hy = (d-c)/ny 

    first_term = (f(a,c)+f(a,d)+f(b,c)+f(b,d))

    i_sum = 0
    for i in range(1,ny):
        i_sum += f(a,c+i*hy)+f(b, c+i*hy)

    j_sum = 0
    for j in range(1,nx):
        j_sum += f(a+j*hx,c)+f(a+j*hx,d)

    ij_sum = 0
    for i in range(1,ny):
        for j in range(1,nx):
            ij_sum += f(a+j*hx,c+i*hy)

    integral = (first_term/4 + i_sum/2 + j_sum/2 + ij_sum) * hx * hy

    return integral


def t(x,y):
    return x*(y**(2))

print(double_integral(t,0,2,0,1,10,10))

0.6700000000000003

You'll get closer to 2/3 by choosing numbers of steps larger than 10 ...

And you can be more pythonic by using sum comprehension:

def double_integral(f,a,b,c,d,nx,ny):
    hx = (b-a)/nx
    hy = (d-c)/ny 
    first_term = (f(a,c)+f(a,d)+f(b,c)+f(b,d))
    i_sum = sum(f(a,c+i*hy)+f(b, c+i*hy) for i in range (1,ny))
    j_sum = sum(f(a+j*hx,c)+f(a+j*hx,d) for j in range(1,nx))
    ij_sum = sum(f(a+j*hx,c+i*hy) for i in range (1,ny) for j in range(1,nx))
    integral = (first_term/4 + i_sum/2 + j_sum/2 + ij_sum) * hx * hy
    return integral

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM