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

1 Answer

0 votes
#include <iostream>
#include <random>
#include <vector>
#include <iomanip>

// 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:
 *   - Creates a random engine (Mersenne Twister)
 *   - Uses std::normal_distribution to generate values
 *   - mean = 1.0, stddev = 1.0 (can be changed)
 *   - Returns a vector of 100 normally distributed numbers
 */
std::vector<double> generateNormalValues(int total) {
    std::random_device rd;          // Non‑deterministic seed
    std::mt19937 gen(rd());         // Fast Mersenne Twister engine

    double mean = 1.0;
    double stddev = 1.0;

    std::normal_distribution<double> dist(mean, stddev);

    std::vector<double> values;
    values.reserve(total);

    for (int i = 0; i < total; i++) {
        values.push_back(dist(gen));
    }

    return values;
}

/*
 * printValues:
 *   - Prints all generated numbers with formatting
 */
void printValues(const std::vector<double>& values) {
    for (double v : values) {
        std::cout << std::fixed << std::setprecision(4) << v << "\n";
    }
}

int main() {
    auto values = generateNormalValues(100);
    printValues(values);
    
    return 0;
}


/*
run:

1.2867
0.8375
2.0484
0.9072
1.3893
1.4536
-0.2186
0.7842
0.8877
0.5280
1.9419
1.2115
-0.9248
1.3660
1.7949
2.2908
0.8878
2.2760
2.1847
0.4262
0.0477
0.0124
1.7632
-0.1310
-0.9047
1.1542
0.7348
1.4633
0.3752
1.6302
0.3243
0.1680
2.3532
1.7138
0.6327
1.3591
2.1522
2.4506
0.2193
1.7264
0.8994
2.5302
1.2829
1.8642
1.4388
0.5979
1.4918
2.4791
0.6446
0.8560
1.1472
2.2505
-0.5491
1.6980
0.4830
0.0912
2.6684
1.4341
0.9417
1.3766
2.3917
0.2224
-0.4036
1.7462
1.5849
1.7286
0.5542
0.3652
1.1820
1.2275
1.2469
0.0131
1.0397
-0.9010
0.2781
0.5520
1.7910
1.3447
1.0759
0.2051
2.3302
1.5504
1.1238
0.6526
-0.7840
1.3740
1.4801
-0.3677
1.1332
0.8681
0.4065
0.0581
0.7131
1.0650
1.6486
-1.0941
1.1226
0.9081
-0.6923
1.3198

*/

 



answered Jul 8 by avibootz
edited Jul 8 by avibootz
...