- 论坛徽章:
- 0
|
对于独立事件,P(AB)=P(A)P(B),所以只需调用两次foo,P(0,1)与P(1,0)的概率都是0.24,由此就可得到一个等概率。这样当(0,1)出现时返回0,当(1,0)出现时,返回1。- /**
- * File:MyFoo.java
- * -----------------
- * P(0,1)=P(0)*P(1)=0.6*0.4=0.24
- * P(1,0)=P(1)*P(0)=0.4*0.6=0.24
- * P(0,1)=P(1,0)
- */
- package org.cudemo;
- /**
- * @author isaacxu
- *
- */
- public class MyFoo {
-
- public static void main(String[] args) {
- int val = myfoo();
- System.out.println(val);
- }
-
- // foo that returns 0 by 0.6 and 1 by 0.4
- static int foo()
- {
- int i=0;
- // some code here
- return i;
- }
-
- // returns 0 and 1 by 0.5 probability
- static int myfoo()
- {
- int returnVal= 0;
- int firstCall = foo();
- int secondCall = foo();
- //get pair (0,1) or (1,0)
- while(firstCall==secondCall){
- firstCall = foo();
- secondCall = foo();
- }
-
- if (firstCall == 0 && secondCall == 1)
- returnVal= 0; // get 0.24 probability
- if (firstCall == 1 && secondCall == 0)
- returnVal = 1; // get 0.24 probability
- return returnVal;
- }
- }
复制代码 |
|