擷取0到1的隨機數

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   sp   for   

這個網址介紹了很多

http://stackoverflow.com/questions/17598547/why-is-the-first-result-of-rand-doublerand-max-is-not-random

and

http://stackoverflow.com/questions/1340729/how-do-you-generate-a-random-double-uniformly-distributed-between-0-and-1-from-c

 

範圍是0-1

double X=((double)rand()/(double)RAND_MAX);

 

 1 #include <iostream> 2 #include <iomanip> 3 #include <map> 4 #include <random> 5  6 int main() 7 { 8     std::random_device rd; 9 10 11     std::mt19937 e2(rd());12 13     std::uniform_real_distribution<> dist(0, 1);14 15     std::map<int, int> hist;16     for (int n = 0; n < 10000; ++n) {17         ++hist[std::round(dist(e2))];18     }19 20     for (auto p : hist) {21         std::cout << std::fixed << std::setprecision(1) << std::setw(2)22                   << p.first << ‘ ‘ << std::string(p.second/200, ‘*‘) << ‘\n‘;23     }24 }

 

 範圍是0-1

1 #include <stdlib.h>2 3 double randZeroToOne()4 {5     return rand() / (RAND_MAX + 1.);6 }

 

 範圍是M到N

double randMToN(double M, double N){    return M + (rand() / ( RAND_MAX / (N-M) ) ) ;  }

 

擷取0到1的隨機數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.