• 0/1不等概率随机-求->0/1等概率随机


    从一个不等概率,获得等概率

    得到0/1的概率是不等的,得到0的概率是P,得到1的概率是(1-P) 求,如何得到等概率的0/1
    带入实际数字的百分比,得到0的概率是70%,得到1的概率是30%,相加是100%

    第一步

     private int c01() {
     //获得不等概率的随机0/1
        return Math.random() < 0.7 ? 0 : 1;
      }
    
    • 1
    • 2
    • 3
    • 4

    第二步

     /**
     * 筛查2次c01(),如果两次一致,那就重新做,只有0,1或1,0才会返回
     *
     * @return 此时返回的是等概率0,1
     */
    private int c02() {
      int c2;
      do {
        c2 = c01();
      } while (c2 == c01());
      return c2;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    第三步

      /** 测试 */
      @Test
      public void c03() {
        int[] counts = new int[2];
        int num = 1000000;
        for (int i = 0; i < num; i++) {
          int t = c02();
          counts[t]++;
        }
        // 校验
        System.out.println(Arrays.toString(counts));
        System.out.println((double) counts[0] / (double) num);
        System.out.println((double) counts[1] / (double) num);
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    心得:
    对于不等概率,要先找到其中的等概率,
    c01(),获得0是70%,获得1是30%,这是前提条件
    c02()中,若第一次==第二次,说明是00或11,概率不能等于100%,只有第一次获得0第二次获得1; 或者第一次获得1,第二次获得0,两个概率想加100%,才能说明是概率一致的.

  • 相关阅读:
    蓝桥杯1044
    使用QMetaObject::invokeMethod来发射信号
    前端框架 Nuxtjs Vue3 SEO解决方案 SSR
    JS 流行框架(二):Express
    MCE | 自噬检测
    Linux介绍
    JSON 教程
    PM2 vs Kubernetes:在部署 Node.js 服务时使用哪个?
    数据库版本控制|一文带你快速入门
    探讨Morest在RESTful API测试的行业实践
  • 原文地址:https://blog.csdn.net/copyright0501/article/details/127434640