zoukankan      html  css  js  c++  java
  • 【c++】生成浮点随机数

    c++11:std::uniform_real_distribution<>直接求(尖括号不填默认生成double)

    随机10个在1-2之间的浮点数

    #include <random>
    #include <iostream>
     
    int main()
    {
        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(1.0, 2.0);
        for (int n = 0; n < 10; ++n) {
            // Use dis to transform the random unsigned int generated by gen into a 
            // double in [1, 2). Each call to dis(gen) generates a new random double
            std::cout << dis(gen) << ' ';
        }
        std::cout << '
    ';
    }

    结果:

    1.80829 1.15391 1.18483 1.38969 1.36094 1.0648 1.97798 1.27984 1.68261 1.57326

    https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution

    c++11 之前:通过std::rand()和RAND_MAX间接求

    如果要实现0-1之间随机浮点数的函数,可以如下: 

    double randf() { 
         return (double)(rand()/(double)RAND_MAX); 
    } 

    https://blog.csdn.net/enterlly/article/details/54310945

  • 相关阅读:
    5.14事务
    5.13Mysql数据库Database
    未来打算
    浅谈P NP NPC
    1222
    1219
    Linux初等命令
    惩罚因子(penalty term)与损失函数(loss function)
    12 14
    java 泛型思考
  • 原文地址:https://www.cnblogs.com/zealousness/p/10324170.html
Copyright © 2011-2022 走看看