对数器学习

代码演示:

package com.ketty;

public class RandomTORandom {

    // 随机等概率返回1~7之间的整数
    public static  int f1(){
        return  (int)(Math.random()*7)+1;
    }

    //等概率实现0~1的对数器
    public static int f2(){
        int ans=0;
        do {
            ans=f1();
        }while (ans==4);
        return ans< 4?0:1;
    }

    //做到000~1111为等概率 0~15
    public static int f3(){
        return (f2()<<0)+(f2()<<1)+(f2()<<2)+(f2()<<3);
    }

    //做到 0~9 之间的等概率 大于9,重新跑
    public static int f4(){
        int ans=0;
        do {
            ans=f3();
        }while (ans>9);
        return ans;
    }
    //做到 1~10 之间的等概率
    public static int g(){
        return f4()+1;
    }

    public static void printNum(){
        int[] count=new int[11];
        for (int i = 0; i < 10000000; i++) {
            int num=g();
            count[num]++;
        }

        for (int i = 0; i < 11; i++) {
            System.out.println(i+"这个数,出现了"+count[i]+"次");
        }
    }

    //验证 0~1 对数器的概率
    public static void fx(){
        int count1=0,count2=0;
        for (int i = 0; i < 1000000; i++) {
            if (f2()==0){
                count1++;
            }else{
                count2++;
            }
        }
        System.out.println((double) count1/(double)1000000);
        System.out.println((double)count2/(double)1000000);
    }

    //打印1~10随机整数的概率
    public static void main(String[] args) {
        printNum();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孺子韫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值