`
dimple
  • 浏览: 94410 次
  • 性别: Icon_minigender_1
  • 来自: 辽宁
社区版块
存档分类
最新评论

控制随机率的精简算法

阅读更多

如果控制十个数的随机率,可以先把这10个数放在一个数组里面,然后得到的随即数模上10,则得到几率相等的1-9作为数组的下标,就可以实现平均概率取得数组里的十个数.

例如:

import java.util.Random;
public class Test
{


    public static void main(String[] args)
    {
       
        int countOne=0;
        int countTwo=0;
        int countThree=0;
        for(int i=0;i<100000;i++)
        {
            long rand=Math.round(Math.random()*100000)%3;
            if(rand==0)
            {
                countOne++;
            }else if(rand==1)
            {
                countTwo++;
            }else
            {
                countThree++;
            }
        }
        System.out.println("1: "+countOne);
        System.out.println("2: "+countTwo);
        System.out.println("3: "+countThree);
    }

}

误差率为千分之二,还算可以.绝对节省资源,速度也不错.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics