简体   繁体   English

Python中的数值方法-无法发现问题?

[英]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 注意hx =(ba)/ nx,hy =(dc)/ ny以获取间隔宽度,xj = a + hx j和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. 然后,仅当在相应的总和中时才应在for添加一个术语...在这里,您将所有内容都放入double for循环中,这与将所有术语都包含在double sum中相对应。

Finally range(1,n) already stops at n-1 only so you want to remove those -1 in the ranges. 最后, range(1,n)仅在n-1处停止,因此您要删除范围中的那些-1

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 ... 通过选择大于10的步数,您将接近2/3 ...

And you can be more pythonic by using sum comprehension: 通过使用sum理解,您可以变得更加Python化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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