内存错误 Python
Memory Error Python
我正在尝试处理 Monte Carlo 算法来计算 pi 的值。当我尝试像下面的程序中提到的那样提供大量输入时。我收到内存错误。我应该怎么做才能纠正它?代码如下:
def PiCalc():
N_ok=0
n=1000000000000
for i in range(n):
x=random()
y=random()
if sqrt(x**2 + y**2) <= 1:
N_ok+=1
pi= 4.0 * N_ok / n
print "No. of points inside the circle: ", N_ok
print "Pi: ", pi
return pi
In Python 2.7 range(n)
将创建一个包含 1000000000000 个元素的列表,这导致 MemoryError
使用 xrange(n)
你可以随时生成项目
根据文档:
xrange(start, stop[, step])
This function is very similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them)
由于您使用 print
的方式,我假设您正在使用 Python 2.x。在Python2.x、range
returns一个列表中。所以你试图在内存中构建一个包含 1000000000000 个整数的列表。这里内存错误是正常的。
你应该试试:
for i in xrange(n):
因为 xrange
returns 一个 xrange 对象 (*) 并且不会在内存中构建列表。
(*) 它允许迭代值,但它并不是真正的迭代器(感谢 DSM 的精度)
鉴于没有人提到这个...
您也可以使用itertools.repeat(None, n)
。这将比 range
和 xrange
都快得多,因为它不会创建一万亿个新的 int
实例。
使用 repeat()
,您的 for 循环变为:
for _ in itertools.repeat(None, n):
x=random()
y=random()
if x**2 + y**2 <= 1:
N_ok += 1
我会创建一个函数:
def random_pairs(n):
for _ in itertools.repeat(None, n):
yield random(), random()
N = sum(1 for (x, y) in random_pairs(n)
if x**2 + y**2 <= 1.)
我正在尝试处理 Monte Carlo 算法来计算 pi 的值。当我尝试像下面的程序中提到的那样提供大量输入时。我收到内存错误。我应该怎么做才能纠正它?代码如下:
def PiCalc():
N_ok=0
n=1000000000000
for i in range(n):
x=random()
y=random()
if sqrt(x**2 + y**2) <= 1:
N_ok+=1
pi= 4.0 * N_ok / n
print "No. of points inside the circle: ", N_ok
print "Pi: ", pi
return pi
In Python 2.7 range(n)
将创建一个包含 1000000000000 个元素的列表,这导致 MemoryError
使用 xrange(n)
你可以随时生成项目
根据文档:
xrange(start, stop[, step]) This function is very similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them)
由于您使用 print
的方式,我假设您正在使用 Python 2.x。在Python2.x、range
returns一个列表中。所以你试图在内存中构建一个包含 1000000000000 个整数的列表。这里内存错误是正常的。
你应该试试:
for i in xrange(n):
因为 xrange
returns 一个 xrange 对象 (*) 并且不会在内存中构建列表。
(*) 它允许迭代值,但它并不是真正的迭代器(感谢 DSM 的精度)
鉴于没有人提到这个...
您也可以使用itertools.repeat(None, n)
。这将比 range
和 xrange
都快得多,因为它不会创建一万亿个新的 int
实例。
使用 repeat()
,您的 for 循环变为:
for _ in itertools.repeat(None, n):
x=random()
y=random()
if x**2 + y**2 <= 1:
N_ok += 1
我会创建一个函数:
def random_pairs(n):
for _ in itertools.repeat(None, n):
yield random(), random()
N = sum(1 for (x, y) in random_pairs(n)
if x**2 + y**2 <= 1.)