C++生成给定范围内的随机数并输出到文件

#include <random>
#include <fstream>
#include <iostream>
using namespace std;

int randInt(int low, int high)
{
    
    
    static std::random_device rd;  //Will be used to obtain a seed for the random number engine
    static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dis(low, high);
    return dis(gen); // generate random int [low, high]
}

int main()
{
    
     
    ofstream write("D:\\data.txt");
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_real_distribution<> dis(-2.0, 2.0);
    for (int n = 0; n < 100; ++n) {
    
    
        double decimal = dis(gen);
        if (n % 2 != 0)
            write << decimal << "    ";
        else
            write << decimal << endl;
    }      
    write.close();
    return 0;
}

或者使用线性同余数发生器,生成的数满足 x i + 1 = A x i m o d M x_{i+1} = Ax_{i} mod M xi+1=AximodM。这个序列需要 x 0 x_{0} x0 的某个值,这个值叫作种子,一般取 x 0 x_{0} x0 1 1 1。使用 M = 2147483647 , A = 48271 M = 2147483647, A = 48271 M=2147483647,A=48271 能产生很好的随机数。

#ifndef RANDOM_H
#define RANDOM_H

static const int A = 48271;
static const int M = 2147483647;
static const int Q = M / A;
static const int R = M % A;

class Random
{
    
    
public:
    explicit Random(int initialValue = 1);
    int randomInt();
    double random0_1();
    int randomInt(int low, int high);

private:
    int state;
};

Random::Random(int initialValue)
{
    
    
    if (initialValue < 0)
        initialValue += M;
    state = initialValue;
    if (state == 0)
        state = 1;
}

int Random::randomInt()
{
    
    
    int tmpState = A * (state % Q) - R * (state / Q);
    if (tmpState >= 0)
        state = tmpState;
    else
        state = tmpState + M;
    return state;
}

double Random::random0_1()
{
    
    
    return static_cast<double>(randomInt()) / M;
}

int Random::randomInt(int low, int high)
{
    
    
    double partitionSize = static_cast<double>(M) / (high - low + 1);
    return static_cast<int>(randomInt() / partitionSize) + low;
}

#endif

#include "Random.h"
#include <fstream>
#include <iostream>
using namespace std;

int main( )
{
    
    
    ofstream write("D:\\data.txt");
    Random r{
    
    1};
    for (int i = 0; i < 100; ++i)
        write << r.randomInt(0, 1000) << endl;
    write.close();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_18431031/article/details/107417423