如何使用C中的函数生成随机数组 [英] How to generate array of random numbers using functions in C

查看:170
本文介绍了如何使用C中的函数生成随机数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将程序从Matlab移植到C以提高执行时间和内存使用率。
由于C中没有生成0和1的统一填充数组的函数(或者我找不到它们),所以我创建了一个函数来根据相关概率填充数组。



示例:如果概率为0.3(30%)我想要一个由100个元素组成的数组,随机填充 ones ,并且数组之和必须接近30。



而不是100我使用N =试验次数,所以如果N = 10000,那么数组的总和应该接近3000等。



Matlab中的函数只是:
$ (i,1)= b $ b pre $函数[y] = rand_gen(N,Prob)

binornd(1,习题);
end
end

该函数将被称为:

  array = rand_gen(N,Probability); 

现在,这里是C语言中的问题:当我运行程序时,我可以生成一些数组,最大审判次数(N)非常低,我不认为它是一个记忆问题。如果我用N = 100000运行程序,一切正常,但100000(和某些事件)崩溃后。
C中的程序是:

  #include< stdio.h> 
#include< stdlib.h>
#include< time.h>

int * rand_gen(int N,double Prob); //函数声明
int sum_array(int a [],int num_elements); //函数声明

int main()//主函数
{
int N; //声明:审判次数
printf(审判次数:);
scanf(%d,& N); //询问试验次数

double Prob_a = 0.5; //概率(50%)
int i; //声明:索引
int sum; //声明:数组元素的总和
int bin_array_0 [N]; //声明:数组由0和1随机填充
int bin_array_1 [N]; //声明:数组由0和1随机填充
int bin_array_2 [N]; //声明:数组由0和1随机填充
int bin_array_3 [N]; //声明:数组由0和1随机填充
int * ptrnd = NULL; //声明:指向数组
的指针int seed = time(NULL); //声明:随机数发生器种子(基于当前时间)
srand(seed);


ptrnd = rand_gen(N,Prob_a); //使用rand_gen函数为0和1填充临时数组
$ b for(i = 0; i {
bin_array_0 [i] = *( ptrnd + i);
}
/ *为了检查rand_gen概率
*可靠性并与临时数组进行比较,在数组
*中输出数值之和* /
sum = sum_array(bin_array_0,N);
printf(\\\
bin_array_0的总和为%d \ n,sum);



ptrnd = rand_gen(N,Prob_a); //使用rand_gen函数为0和1填充临时数组
$ b for(i = 0; i {
bin_array_1 [i] = *( ptrnd + i);
}
/ *为了检查rand_gen概率
*可靠性并与临时数组进行比较,在数组
*中输出数值之和* /
sum = sum_array(bin_array_1,N);
printf(\\\
bin_array_1的总和为%d \ n,sum);


ptrnd = rand_gen(N,Prob_a); //使用rand_gen函数为0和1填充临时数组
$ b for(i = 0; i {
bin_array_2 [i] = *( ptrnd + i);
}
/ *为了检查rand_gen概率
*可靠性并与临时数组进行比较,在数组
*中输出数值之和* /
sum = sum_array(bin_array_2,N);
printf(\\\
bin_array_2的总和是%d \ n,sum);


ptrnd = rand_gen(N,Prob_a); //使用rand_gen函数为0和1填充临时数组
$ b for(i = 0; i {
bin_array_3 [i] = *( ptrnd + i);
}
/ *为了检查rand_gen概率
*可靠性并与临时数组进行比较,在数组
*中输出总和$ /
* = sum_array(bin_array_3,N);
printf(\\\
bin_array_3的总和为%d \ n,sum);

return(0);




//功能:根据统一分布生成一个由0和1填充的数组
int * rand_gen(int N,double Prob)
{
int sum; //声明:数组元素的总和
int * array;
array =(int *)malloc(sizeof(int)* N);
if(array == NULL)
{
printf(\\\
Run memory of memory!\\\
);
exit(1);
}

int j;
double x; (j = 0; j {
x = rand();


x = x / RAND_MAX;
if(x {
array [j] = 1;
}
else
{
array [j] = 0;



/ *打印数组
*中的总和以检查rand_gen概率
*的可靠性并与bin_array_ * * /
sum = sum_array(array,N);
printf(\\\
temp数组的总和为%d \ n,sum);

返回数组;
}


//功能:对数组的元素进行求和并返回总和。
int sum_array(int a [],int num_elements)
{
int k,sum = 0; (k = 0; k {
sum = sum + a [k];
}
return(sum);
}

请给我一些提示如何解决问题。我已经尝试过使用不同类型的值( long 而不是 int double ,而不是 float ),但没有任何结果。
先谢谢您!

干杯,

Pullo86


填充,并让它写入,而不是让它分配大型数组,然后复制和泄漏。 (这是一个应用程序,C ++ STL与< random> < vector> 可能是)



然而,如果您想使用这个基本结构,请声明:

  #include< stdbool.h> 
#include< stdio.h>
#include< stdlib.h>

/ *设置N. * /

bool * binarray [] = {
rand_gen(N,prob_a),// binarray [0]
rand_gen(N,prob_a),
rand_gen(N,prob_a),
rand_gen(N,prob_a)// binarray [3]
};
static const size_t m = sizeof(binarray)/ sizeof(binarray [0]);

/ *通过binarray [m-1]做binarray [0]。 * /

for(size_t i = 0; i free(binarray [i]);
binarray [i] = NULL;

$ / code>

实际上,您可能需要一组数组,您的随机生成器更新到位,如下所示:

  bool * fill_arrays(size_t m,size_t n,bool to_fill [m] [n], (size_t i = 0; i< m; ++ i)
rand_gen_in_place(to_fill [i],n,prob)的
{
;

返回to_fill;
}

void do_stuff_with(size_t m,size_t n,bool binarray [m] [n]);

int main(void)
{
/ * ... * /
bool * arrayp = calloc(M * N,sizeof(bool));
fill_arrays(M,N,arrayp,prob_a);
do_stuff_with(M,N,arrayp);
free(arrayp);
/ * ... * /
}


I am trying to port a program from Matlab to C in order to improve the execution time and the memory usage. Since there are not functions in C which generate uniformly populated arrays of 0 and 1 (or I could not find them) I created a function to populate an array accordingly to the associated probability.

Example: if the probability is 0.3 (30%) I would like to have an array of 100 elements, populated randomly with zeros and ones, and the sum of ones of the array must be close to 30.

Instead of 100 I use N = number of trials, so if N=10000 then the sum of ones of the array should be something close to 3000, etc.

The function in Matlab is just:

function [y] = rand_gen(N,Prob)

    for i=1:N
        y(i,1) = binornd(1,Prob);
    end
end

The function would be called as:

array = rand_gen(N, Probability);

Now, here is the issue in C: when I run the program I can generate some arrays but the maximum number of trials (N) its very low, and I don't think its a matter of memory. If I run the program with N = 100000 everything goes ok, but after 100000 (and something) crashes. The program in C is:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int * rand_gen(int N, double Prob); // Function declaration
int sum_array(int a[], int num_elements);    // Function declaration

int main()  // Main function
{
int N;  // Declaration: Number of trials
printf("Number of trials: ");
scanf("%d", &N);    // Asks for Number of trials

double Prob_a = 0.5;   // Probability (50%)
int i;  // Declaration: Index
int sum; // Declaration: sum of elements of arrays
int bin_array_0[N]; // Declaration: array populated randomly by 0 and 1
int bin_array_1[N]; // Declaration: array populated randomly by 0 and 1
int bin_array_2[N]; // Declaration: array populated randomly by 0 and 1
int bin_array_3[N]; // Declaration: array populated randomly by 0 and 1
int *ptrnd = NULL; // Declaration: pointer to array
int seed = time(NULL); // Declaration: random number generator seed (based on current time)
srand(seed);


ptrnd = rand_gen(N, Prob_a);    // Populate a temporary array with 0 and 1 using the rand_gen function

for(i=0 ; i<N ; i++)
{
    bin_array_0[i] = *(ptrnd + i);
}
/* Print the sum of ones in the array
 * in order to check the rand_gen probability
 * reliability and compare to the temp array   */
sum = sum_array(bin_array_0, N);
printf("\n The sum of the bin_array_0 is %d\n", sum);



ptrnd = rand_gen(N, Prob_a);    // Populate a temporary array with 0 and 1 using the rand_gen function

for(i=0 ; i<N ; i++)
{
    bin_array_1[i] = *(ptrnd + i);
}
/* Print the sum of ones in the array
 * in order to check the rand_gen probability
 * reliability and compare to the temp array   */
sum = sum_array(bin_array_1, N);
printf("\n The sum of the bin_array_1 is %d\n", sum);


ptrnd = rand_gen(N, Prob_a);    // Populate a temporary array with 0 and 1 using the rand_gen function

for(i=0 ; i<N ; i++)
{
    bin_array_2[i] = *(ptrnd + i);
}
/* Print the sum of ones in the array
 * in order to check the rand_gen probability
 * reliability and compare to the temp array   */
sum = sum_array(bin_array_2, N);
printf("\n The sum of the bin_array_2 is %d\n", sum);


ptrnd = rand_gen(N, Prob_a);    // Populate a temporary array with 0 and 1 using the rand_gen function

for(i=0 ; i<N ; i++)
{
    bin_array_3[i] = *(ptrnd + i);
}
/* Print the sum of ones in the array
 * in order to check the rand_gen probability
 * reliability and compare to the temp array   */
sum = sum_array(bin_array_3, N);
printf("\n The sum of the bin_array_3 is %d\n", sum);

return(0);

}


// Function: generate an array populated by 0 and 1 according to a uniformed distribution
int * rand_gen(int N, double Prob)
{
    int sum; // Declaration: sum of elements of arrays
    int *array;
    array = (int *)malloc(sizeof(int)*N);
    if(array == NULL)
    {
        printf("\nRun out of memory!\n");
        exit(1);
    }

    int j;
    double x;

    for(j=0; j<N; j++)
    {
        x=rand();
        x=x/RAND_MAX;
        if (x < Prob)
        {
            array[j]=1;
        }
        else
        {
            array[j]=0;
        }
    }

/* Print the sum of ones in the array
 * in order to check the rand_gen probability
 * reliability and compare to the bin_array_*   */
    sum = sum_array(array, N);
    printf("\n The sum of the temp array is %d\n", sum);

    return array;
}


// Function: sum elements of array and return the sum.
int sum_array(int a[], int num_elements)
{
    int k, sum=0;
    for (k=0; k<num_elements; k++)
        {
        sum = sum + a[k];
        }
    return(sum);
}

Please give me some tips how to solve the issue. I have already tried with different types of values (long instead of int and double instead of float) but without any result. Thank you in advance!

Cheers,

Pullo86

解决方案

What you almost certainly want to do is pass rand_gen() a pointer to the array it’s to be filling, and have it write to that, rather than have it allocate large arrays which it then copies and leaks. (This is an application for which the C++ STL, with <random> and <vector>, might be better-suited.)

If you want to use this basic structure, though, declare:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/* Set N. */

bool *binarray[] = {
  rand_gen( N, prob_a ), // binarray[0]
  rand_gen( N, prob_a ), 
  rand_gen( N, prob_a ),
  rand_gen( N, prob_a )  // binarray[3]
};
static const size_t m = sizeof(binarray)/sizeof(binarray[0]);

/* Do stuff with binarray[0] through binarray[m-1]. */

for ( size_t i = 0; i < m; ++i ) {
  free(binarray[i]);
  binarray[i] = NULL;
}

In practice, though, you probably want an array of arrays that your random generator updates in place, something like:

bool *fill_arrays( size_t m, size_t n, bool to_fill[m][n], double prob )
{
  for ( size_t i = 0; i < m; ++i )
    rand_gen_in_place( to_fill[i], n, prob );

  return to_fill;
}

void do_stuff_with( size_t m, size_t n, bool binarray[m][n] );

int main(void)
{
  /* … */
  bool* arrayp = calloc( M*N, sizeof(bool) );
  fill_arrays( M, N, arrayp, prob_a );
  do_stuff_with( M, N, arrayp );
  free(arrayp);
  /* … */
}

这篇关于如何使用C中的函数生成随机数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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