种子随机数生成器C ++ [英] Seeding a random number generator C++

查看:933
本文介绍了种子随机数生成器C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题。

I have two questions.


  1. 有什么其他方法可以在C ++中种一个伪随机数生成器而不使用 srand时间(NULL))

我问第一个问题的原因。我目前使用时间作为我的种子为我的发电机,但发电机返回的数字总是相同的。我很确定原因是因为存储时间的变量在某种程度上被截断。 (我有一个警告消息说,隐式转换失去整数精度:'time_t'(aka'long')到'unsigned int')我想这是告诉我,从本质上,我的种子将不会改变,直到明年为了我的目的,使用时间,因为我的种子会正常工作,但我不知道如何摆脱这个警告。

The reason I asked the first question. I'm currently using time as my seed for my generator, but the number that the generator returns is always the same. I'm pretty sure the reason is because the variable that stores time is being truncated to some degree. (I have a warning message saying, "Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int') I'm guessing that this is telling me that in essence my seed will not change until next year occurs. For my purposes, using time as my seed would work just fine, but I don't know how to get rid of this warning.

我以前从来没有得到过这个错误信息,所以我认为它与我的Mac有关系。它是64位OS X v10.8。我也使用Xcode编写和编译,但是,我在其他有Xcode的计算机上没有问题。

I have never gotten that error message before, so I assume it has something to do with my Mac. It's 64-bit OS X v10.8. I'm also using Xcode to write and compile, but I had no problems on other computers with Xcode.

编辑:
经过研究和研究之后,我发现了一个64位如果你试图让你的mac使用时间(NULL)作为种子选择1到7之间的随机数,你总会得到第四个,总是,我最后使用 mach_absolute_time()种子我的randomizer。显然,这消除了所有的可移植性从我的程序...但我只是一个爱好者。

After toying and researching this more, I discovered a bug that 64-bit Macs have. (Please correct me if I am mistaken.) If you try to have your mac select a random number between 1 and 7 using time(NULL) as the seed, you will always get the number four. Always. I ended up using mach_absolute_time() to seed my randomizer. Obviously this eliminates all portability from my program... but I'm just a hobbyist.

Edit2:
源代码:

Source code:

#include <iostream>
#include <time.h>

using namespace std;

int main(int argc, const char * argv[]) {

srand(time(NULL));

cout << rand() % 7 + 1;

return 0;
}

我再次运行此代码来测试它。现在它只返回3.这必须是与我的电脑,而不是C + +本身。

I ran this code again to test it. Now it's only returning 3. This must be something to do with my computer and not the C++ itself.

推荐答案

1.不是真的。例如,您可以要求用户输入随机种子。或者使用一些其他系统参数,但这不会有所作为。

1.Not really. You can ask user to input random seed, for example. Or use some other system parameters, but this won't make a difference.

2.要摆脱这个警告,你必须做显式转换。 Like:

2.To rid of this warning you have to do explicit conversion. Like:

unsigned int time_ui = unsigned int( time(NULL) );
srand( time_ui );

unsigned int time_ui = static_cast<unsigned int>( time(NULL) );

unsigned int time_ui = static_cast<unsigned int>( time(NULL)%1000 );

来检查这是否真的是转换问题,你可以简单地在屏幕上输出您的时间, / p>

to check whether this is really conversion problem you can simply output your time on the screen and see yourself

std::cout << time(NULL);

这篇关于种子随机数生成器C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆