Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

python - How to use `nquad` with specific weight function?

Right now I need to calculate the integral of f(x)(x-a)(y-c), with x from a to b and y from c to d numerically. I've checked the docs of scipy.integrate.nquad, and I believe the parameter weight=alg with wvar=(1,0) should work.

Here is what I've tried so far:

import numpy as np
from scipy import integrate


def f(x, y):
    return -2 * y


t = 0.02

res, err = integrate.nquad(
    f, [[0, t], [0, t]], opts=[{'weight': 'alg', 'wvar': (1, 0)}, {'weight': 'alg', 'wvar': (1, 0)}])

res1, err = integrate.quad(lambda x: 1, 0, t, weight='alg', wvar=(1, 0))
res2, err = integrate.quad(lambda y: -2 * y, 0, t, weight='alg', wvar=(1, 0))
print(res)
print(res1*res2)

where I chose a=c=0,b=d=0.02 and f(x,y)=-2y for simplicity.

The two results should be the same in that

$int_0^t (int_0^t(-2y)xy dx) dy=(int_0^txdx)(int_0^t(-2y^2)dy)=-frac{1}{3}t^5$

holds, but I got the output

-1.014820841542623e-06
-1.0666666666666665e-09

and the second one is correct. It turns out the function quad behaves as expected, while the function nquad does not. So my question is: How to pass the right parameters to nquad?

Any help would be appreciated.

question from:https://stackoverflow.com/questions/65869209/how-to-use-nquad-with-specific-weight-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...