我尝试使用蒙特卡罗方法近似三重积分∫∫∫xyzdV,其中S = [0,1]×[0,1]×[0,1]。 我有这段代码:
from numpy import *
import time
from scipy.integrate import tplquad
numpoints=100000 # number of random sample points
I2d=0.0 # initialize value
I2dsquare=0.0 # initialize to allow for calculation of variance
for n in xrange(numpoints):
x=random.uniform()
y=random.uniform()
z=random.uniform()
func = lambda x,y,z: x*y*z
x1,x2 = 0, 1
y1,y2 = lambda x: 0,lambda x: 1
z1,z2 = lambda x, y: 0,lambda x, y: 1
I2d += tplquad(func, x1,x2,y1,y2,z1,z2)
I2dsquare += (tplquad(func, x1,x2,y1,y2,z1,z2))**2
I2d=I2d/numpoints
I2dsquare=I2dsquare/numpoints
EstimError=4*sqrt( (I2dsquare - I2d**2)/numpoints) # estimated error
I2d=4*I2d
print "Value: %f" %I2d
print "Error estimate: %f" %EstimError
我有这个错误:
Traceback (most recent call last): for n in xrange(numpoints):
File "", line 1, in <module>
File "/tmp/tmpx_9bf5/___code___.py", line 17, in <module>
I2d += tplquad(func, x1,x2,y1,y2,z1,z2)
File "element.pyx", line 999, in sage.structure.element.ModuleElement.__iadd__ (sage/structure/element.c:8285)
File "coerce.pyx", line 797, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (sage/structure/coerce.c:7467)
TypeError: unsupported operand parent(s) for '+': 'Real Field with 53 bits of precision' and '<type 'tuple'>'
我知道此代码中有不同的类型,但我不明白如何解决它。例如,如果我尝试为二次方程式执行此代码,则一切正常,但不幸的是,积分不起作用。
答案 0 :(得分:1)
请看这里:https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.integrate.tplquad.html
scipy.integrate.tplquad
会返回元组(y, abserr)
。
我想你想要这个:
I2d += tplquad(func, x1,x2,y1,y2,z1,z2)[0]
(我不是在数学上完全理解这个问题所以我希望它没有错。)