How to generate 100 normally distributed random numbers with a mean of 1.0 in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

// The mean of 1.0 in a normal distribution is the value around 
// which your random numbers tend to cluster.

/*
Most values fall near 1.0
Because normal distributions cluster around the mean, you’ll see many values like:

0.8
1.2
0.9
1.4

These are all “near” 1.0.
*/


/*
 * generateNormalValues:
 *   - Uses the Box–Muller transform to generate normal values
 *   - mean = 1.0, stddev = 1.0 (can be changed)
 *   - Returns an array of 100 normally distributed numbers
 */
void generateNormalValues(double *values, int total) {
    double mean = 1.0;
    double stddev = 1.0;

    for (int i = 0; i < total; i++) {
        // Box–Muller transform:
        double u1 = (rand() + 1.0) / (RAND_MAX + 2.0);
        double u2 = (rand() + 1.0) / (RAND_MAX + 2.0);

        double z0 = sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2);

        values[i] = mean + stddev * z0;
    }
}

/*
 * printValues:
 *   - Prints all generated numbers with formatting
 */
void printValues(const double *values, int total) {
    for (int i = 0; i < total; i++) {
        printf("%.4f\n", values[i]);
    }
}

int main() {
    srand((unsigned)time(NULL));

    int total = 100;
    double values[100];

    generateNormalValues(values, total);
    printValues(values, total);

    return 0;
}


/*
run:

1.5288
1.6605
1.5834
0.4451
0.5139
2.2265
-0.2237
-0.3862
1.4800
0.4089
3.0193
1.8217
2.3089
2.6101
2.5408
0.4078
0.8172
1.3147
1.3362
0.6175
1.0543
2.4289
0.6588
-0.6280
0.1620
0.9490
-0.0102
2.4300
-0.2429
0.9393
0.4171
0.3601
-1.2633
-1.1353
1.5457
1.1407
2.2478
1.5917
2.4330
0.0563
0.0936
1.2555
1.3724
-0.2832
2.0445
2.7854
1.8550
-0.1658
0.1865
1.2726
1.1375
1.4478
0.2163
2.7057
1.7659
2.1889
1.6692
1.3979
-0.3237
1.1401
0.3104
1.0907
0.9550
-0.8029
1.4825
0.1652
0.5972
0.2964
0.9845
0.1468
1.7877
1.8137
0.8106
-1.2477
-0.1990
-0.6066
1.9981
2.0835
-0.3579
1.6084
0.9942
-0.0468
1.7931
0.4526
1.4248
-0.3183
0.8018
0.9343
0.4452
0.2620
1.2646
0.9724
0.4866
-0.2743
1.6500
0.2378
1.2209
1.2274
1.7335
1.7719

*/

 



answered 6 days ago by avibootz
...