How does Java implement a function so that the probability of return is the same
This article "Java how to achieve a function, so that the probability of return is the same" most people do not understand, so the editor summed up the following content, detailed, clear steps, with a certain reference value, I hope you can get something after reading this article, let's take a look at this "Java how to achieve a function, so that the probability of return is the same" article.
Topic: give a function that returns 0 and 1, and the probability is p and 1. Please implement a function so that the probability of returning 01 is the same.
Idea: if you call the underlying random function twice in a row, there are four results:
1, 00 probability is pumped
2. The probability of 11 is (1m / p) * (1m / p)
The probability of 3 and 10 is (1m / p) * p
4. The probability of 01 is p * (1murp). It can be seen that the probability of result 3 and result 4 are equal.
Public class SameProbability {
/ * *
* the probability of generating 0 is p, and the probability of generating 1 is 1merp.
*
* the probability of generating 0 1 is p (1murp)
* the probability of generating 1 0 is (1murp) p
* is equal.
, /
Public static int getZeroOrOneSameProbability () {
Random ra = new Random ()
While (true) {
Int I = ra.nextInt (10)
Int j = ra.nextInt (10)
If (I = = 0 & j = = 1) {
Return 1
} else if (I = = 1 & & j = = 0) {
Return 0
} else {
Continue
}
}
}
Public static void main (String [] args) {
Int result = getZeroOrOneSameProbability ()
System.out.println (result)
}
}
The above is about the content of this article on "how to implement a function in Java so that the probability of return is the same". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.