生成范围为(0:10 ^ 12)的整数随机数 [英] Generate integer random numbers from range (0:10^12)

查看:92
本文介绍了生成范围为(0:10 ^ 12)的整数随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成0到10 ^ 12之间的10000个整数随机数. 通常,代码如下所示:

I want to generate 10000 integer random numbers between 0 and 10^12. Usually, the code would look like this:

x <- sample(0:1000000000000,10000,replace=T)

但是我收到以下错误消息:

But I get following error message:

Error in 0:1000000000000 : result would be too long a vector

是否有一种更有效的内存使用方法,而不必为了获取大小为10000的样本而将10 ^ 12的整数放入向量中? 如果没有,有没有办法增加向量的最大大小?我正在使用具有12GB可用RAM的64位操作系统.

Is there a more memory efficient method that doesn't have to put 10^12 integers in a vector just to get a sample of size 10000? If not, is there a way to increase the max size of the vector? I'm working on a 64bit OS with 12GB of free RAM.

推荐答案

真正的问题在于您无法将0:10^12的序列存储到内存中.只要将0和10 ^ 12定义为均匀分布的边界,就可以得到想要的结果:

The real problem lies in the fact that you cannot store the sequence of 0:10^12 into memory. By just defining 0 and 10^12 as boundaries of a uniform distribution, you could get what you seek:

runif(10000, 0, 10^12)
[1] 136086417828 280099797063 747063538991 250189170474 589044594904
[6]  65385828028 361086657969 186271687970 338900779840 649082854623  ........

这将从统一分布中提取(有替换,尽管我怀疑这很重要).

This will draw from the uniform distribution (with replacement, though I doubt that matters).

但是,您看不到的是这些实际上是浮点数.

However, what you cannot see is that these are actually floating numbers.

您可以使用ceiling对其进行四舍五入:

You can use ceiling to round them up:

samp = runif(1, 0, 10^12)
samp
[1] 19199806033
samp == 19199806033
[1] FALSE
ceiling(samp) == 19199806033
[1] TRUE

因此,完整的代码应为:

So the full code would be:

ceiling(runif(10000, 0, 10^12))

进一步挑剔:

请注意,从技术上讲,该值不允许存在0(因为将四舍五入为0.0001),因此您可以从

Note that this technically will not allow 0 to be there (since 0.0001 would be rounded up), so you could just draw from

ceiling(runif(10000, -1, 10^12))

Carl Witthoft 所述,不适合整数大小的数字显然不是整数,因此您不能指望这些数字是整数.与没有小数的相同浮点数相比,您仍然可以依靠它们来评估TRUE.

As Carl Witthoft mentions, numbers that do not fit into the size of an integer will not be integers obviously, so you cannot count on these numbers to be integers. You can still count on them to evaluate to TRUE when compared to the same floating number without decimals though.

这篇关于生成范围为(0:10 ^ 12)的整数随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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