c++ - 在for循环中生成随机 float

标签 c++ random floating-point

我有一个非常简单的 for 循环来生成一些随机 float :

int dim = 6;
int n = 100000;

int size = n * dim;

float data[size],r;
for(int i = 0; i < size; i++)
{
    r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
    data[i] = r;
}

它工作正常,直到我将 n 的大小从 100000 增加到 1000000。这是 ideone 上的完整代码:http://ideone.com/bhOwVr

实际上在我的电脑上它只适用于 n=10000。任何更大的数字都会导致崩溃。没有错误信息。

最佳答案

如果您声明一个固定大小的数组,它将分配在堆栈上。该程序的堆栈内存非常有限。 Here are some examples for default values .还有相关阅读:What and where are the stack and heap?

您可以增加堆栈大小...不推荐但有效:

[luk32@localhost tests]$ g++ ./stack_mem.c 
[luk32@localhost tests]$ ./a.out 
Segmentation fault (core dumped)
[luk32@localhost tests]$ ulimit -s 32768
[luk32@localhost tests]$ ./a.out 
[luk32@localhost tests]$ #it worked.

或者在堆上动态分配内存:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    srand ( time(NULL) );

    int dim = 6;
    int n = 1000000;

    int size = n * dim;

    float *data,r;
    data = new float[size];
    for(int i = 0; i < size; i++)
    {
        r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
        data[i] = r;
    }
    delete[] data;
    return 0;
}

结果:

[luk32@localhost tests]$ g++ ./stack_mem.c 
[luk32@localhost tests]$ ./a.out 
[luk32@localhost tests]$ 

虽然,毕竟我会推荐使用 c++ 功能,例如 vectorrandoms .

关于c++ - 在for循环中生成随机 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782996/

相关文章:

c++ - 如何从 const 成员函数内部递减静态数据成员?

c++ - 如何在我的 C++ 源代码中查找(并替换)所有旧的 C 样式数据类型转换?

java - 保持 SecureRandom (SHA1PRNG) 种子 secret - 在播种前计算哈希值?

c++ - float 的符号

haskell - 如何返回小数点后2位的 float ?

perl - 为什么 perl 这里有浮点错误?

c++ - 使用 C++ 进行十六进制编辑

c++ - 为什么在 NULL 检查后会在指针上调用递归函数?

Runif 未生成均匀分布

c++ - 从 STL 容器中抽取 n 个随机元素(无替换)