在for循环中生成随机浮点数

时间:2015-01-05 15:50:42

标签: c++ random floating-point

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

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。任何更大的数字都会导致崩溃。没有错误消息。

1 个答案:

答案 0 :(得分:2)

如果声明一个固定大小的数组,它将在堆栈上分配。程序的堆栈内存非常有限。 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]$ 

虽然我毕竟建议使用vectorrandoms等c ++功能。