更好的随机算法? [英] Better random algorithm?

查看:207
本文介绍了更好的随机算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个游戏在C ++中,它涉及到填充砖随机布尔值(是或否)是否是或不是由决定兰特()%1 。它不会觉得很随意。

我在启动时使用函数srand 的ctime ,但它似乎是相同的模式上来。

是否有任何的算法,将创建非常随机数?或者我如何可以改善任何建议兰特()

解决方案

真正的随机性往往并不显得很随意。不要期望看到奇怪的运行。

但至少有一个眼前的事情可以做,以帮助是为了避免只使用最低阶位。引述数字食谱在C:

如果你想生成1到10之间的随机整数,你应该总是通过使用高序位,如做

  J = 1 +(INT)(10.0 *(RAND()/(RAND_MAX + 1.0)));
 

,从来没有被任何类似

  J = 1 +(RAND()%10);
 

(其使用较低位)。

另外,你可以考虑使用一个不同的RNG具有更好的性能,而不是。该 Xorshift 算法是一个不错的选择。它的快速和紧凑的的C短短的几行,并应几乎所有的游戏是足够好统计。

I'm making a game in C++ and it involves filling tiles with random booleans (either yes or no) whether it is yes or no is decided by rand() % 1. It doesn't feel very random.

I'm using srand with ctime at startup, but it seems like the same patterns are coming up.

Are there any algorithms that will create very random numbers? Or any suggestions on how I could improve rand()?

解决方案

True randomness often doesn't seem very random. Do expect to see odd runs.

But at least one immediate thing you can do to help is to avoid using just the lowest-order bit. To quote Numerical Recipes in C:

If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

and never by anything resembling

j = 1 + (rand() % 10);

(which uses lower-order bits).

Also, you might consider using a different RNG with better properties instead. The Xorshift algorithm is a nice alternative. It's speedy and compact at just a few lines of C, and should be good enough statistically for nearly any game.

这篇关于更好的随机算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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