所以我做了一个简单的程序,用于数值近似双积分,它接受内积分的边界是函数:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
azm = np.linspace(0, 2 * np.pi)
r, th = np.meshgrid(rad25, azm)
z = np.tile(O_rad25, (r.shape[0], 1))
plt.pcolormesh(th, r, z, norm=colors.LogNorm(O_rad25.min(), O_rad25.max()))
plt.colorbar(label='Number of Molecules')
然而,这是非常缓慢的。当def double_integral(func, limits, res=1000):
t = time.clock()
t1 = time.clock()
t2 = time.clock()
s = 0
a, b = limits[0], limits[1]
outer_values = np.linspace(a, b, res)
c_is_func = callable(limits[2])
d_is_func = callable(limits[3])
for y in outer_values:
if c_is_func:
c = limits[2](y)
else:
c = limits[2]
if d_is_func:
d = limits[3](y)
else:
d = limits[3]
dA = ((b - a) / res) * ((d - c) / res)
inner_values = np.linspace(c, d, res)
for x in inner_values:
t2 = time.clock() - t2
s += func(x, y) * dA
t1 = time.clock() - t1
t = time.clock() - t
return s, t, t1 / res, t2 / res**2
,使得积分是一百万个部分的总和时,运行大约需要5秒钟,但答案只适用于我的经验中的第3个小数。有什么方法可以加快速度吗?
我正在运行以检查积分的代码是
res=1000
积分等于16/9
修改
所以我在coderewiev得到了一个很好的答案,但我仍然被 def f(x, y):
if (4 - y**2 - x**2) < 0:
return 0 #This is to avoid taking the root of negarive #'s
return np.sqrt(4 - y**2 - x**2)
def c(y):
return np.sqrt(2 * y - y**2)
def d(y):
return np.sqrt(4 - y**2)
# b d
# S S f(x,y) dx dy
# a c
a, b, = 0, 2
print(double_integral(f, [a, b, c, d]))
似乎给我错误的答案(见评论)所困扰。有没有人对此有答案?