在 C++ 中从 [0,1] 获取随机双数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19741810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get random double number from [0,1] in C++
提问by nullpointer
I want to generate random double number x
, where: 0 <= x <= 1
:
我想生成随机双数x
,其中0 <= x <= 1
::
double x = ((double) rand() / (RAND_MAX));
Is this the correct way of getting random double number from [0,1] ?
这是从 [0,1] 获取随机双数的正确方法吗?
回答by Zeta
Yes, since std::rand()
returns both 0
and RAND_MAX
. However, if you can use C++11, you can use std::uniform_real_distribution
instead.
是的,因为同时std::rand()
返回0
和RAND_MAX
。但是,如果您可以使用 C++11,则可以std::uniform_real_distribution
改用。
Also don't forget to initialize your random number generator, otherwise you will get the same sequence in every execution. If you use std::rand
, std::srand( std::time(0) )
is almost always sufficient.
也不要忘记初始化你的随机数生成器,否则你会在每次执行中得到相同的序列。如果您使用std::rand
,std::srand( std::time(0) )
几乎总是足够的。
回答by Joachim W
Yes.
是的。
Some parentheses are superfluous though.
不过有些括号是多余的。
And it depends on your application whether you can trust your systems rand(3) function. For serious Monte-Carlo simulations you will need a well-documented random-number generator from a numerical library.
这取决于您的应用程序是否可以信任您的系统 rand(3) 函数。对于严肃的 Monte-Carlo 模拟,您将需要一个来自数值库的有据可查的随机数生成器。
回答by Aayush Gupta
Yep, I believe it will give you 0 and 1 in a random sequence when generated subsequently. But be sure to initialize the random number generator function to avoid getting same sequence again and again.
是的,我相信它会在随后生成时以随机序列为您提供 0 和 1。但是一定要初始化随机数生成器函数,避免一次又一次地得到相同的序列。
回答by Genesis
If you were looking for a random double this is how I achieved it.
如果您正在寻找随机双倍,这就是我实现它的方式。
If you are looking for it in a function I can edit this post.
如果您正在某个函数中寻找它,我可以编辑这篇文章。
rand() is included within stdlib.h
rand() 包含在 stdlib.h 中
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
int main()
{
double num;
double max;
srand(time(NULL));
cout << "Enter a number.";
cin >> max;
num = (((double)rand()*(max) / RAND_MAX) - max) *(-1);
cout << num;
}
回答by Mauro H. Leggieri
Yes but I recommend to cast RAND_MAX to double too:
是的,但我建议也将 RAND_MAX 转换为双倍:
double r = ((double)rand() / (double)(RAND_MAX));
Although sometimes unnecessary, the compiler may automatically cast operators to another type depending on target and source variable types. For e.g:
尽管有时不必要,但编译器可能会根据目标和源变量类型自动将运算符转换为另一种类型。例如:
3.5 / 2 may be equal to 1 and not 1.75 because the divisor is an integer and to avoid this you must do:
3.5 / 2 可能等于 1 而不是 1.75,因为除数是一个整数,为避免这种情况,您必须执行以下操作:
3.5 / 2.0 or 3.5 / (double)2
3.5 / 2.0 或 3.5 /(双)2