在Python中生成和使用数百万个随机数的有效方法 [英] Efficient way to generate and use millions of random numbers in Python

查看:105
本文介绍了在Python中生成和使用数百万个随机数的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个编程项目,该过程涉及一些相当广泛的Python蒙特卡罗模拟,因此将产生大量随机数.几乎所有的人,即使不是全部,都将能够由Python的内置随机模块生成.

I'm in the process of working on programming project that involves some pretty extensive Monte Carlo simulation in Python, and as such the generation of a tremendous number of random numbers. Very nearly all of them, if not all of them, will be able to be generated by Python's built in random module.

我是一个编码新手,不熟悉高效的方法.将所有随机数作为一个列表生成,然后遍历该列表,或者每次调用一个函数时都会生成一个新的随机数,这将是一个很大的循环吗?

I'm something of a coding newbie, and unfamiliar with efficient and inefficient ways to do things. Is it faster to generate say, all the random numbers as a list, and then iterate through that list, or generate a new random number each time a function is called, which will be in a very large loop?

还有其他无疑更聪明的方法吗?

Or some other, undoubtedly more clever method?

推荐答案

每次都生成一个随机数.由于循环的内部运作方式只关心单个随机数,因此请在循环内部生成并使用它.

Generate a random number each time. Since the inner workings of the loop only care about a single random number, generate and use it inside the loop.

示例:

# do this:
import random

for x in xrange(SOMEVERYLARGENUMBER):
    n = random.randint(1,1000) # whatever your range of random numbers is
    # Do stuff with n

# don't do this:
import random

# This list comprehension generates random numbers in a list
numbers = [random.randint(1,1000) for x in xrange(SOMEVERYLARGENUMBER)]

for n in numbers:
    # Do stuff with n

很明显,实际上,这并不重要,除非您要处理数十亿次的迭代,但是如果您一次只使用一个,那么为什么还要麻烦生成所有这些数字呢?

Obviously, in practical terms it really doesn't matter, unless you're dealing with billions and billions of iterations, but why bother generating all those numbers if you're only going to be using one at a time?

这篇关于在Python中生成和使用数百万个随机数的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆