Objective-C:模偏差 [英] Objective-C: Modulo bias

查看:17
本文介绍了Objective-C:模偏差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:

value = arc4random() % x

如何避免或消除模偏差?

How can I avoid or eliminate modulo bias?

至少根据维基百科的说法,模偏差在编写机会游戏时是一个问题.

At least according to Wikipedia, modulo bias is an issue when programming games of chance.

推荐答案

arc4random 返回一个 32 位无符号整数(0 到 232-1).

arc4random returns a 32-bit unsigned integer (0 to 232-1).

对于足够小的 x,可能不会有明显的模偏差.但是,如果您想真正确定,请执行以下操作:

There will probably be no noticable modulo bias for small enough x. However, if you want to be really sure, do this:

y = 2p 其中 2p-1 p

y = 2p where 2p-1 < x ≤ 2p

val = arc4random() % y;
while(val >= x)
    val = arc4random() % y;

这篇关于Objective-C:模偏差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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