Random number generator
The random number generator used by the computer is often pseudo-random, in order to achieve the statistical sense of true random number, you can need to introduce system
As random seeds (such as the Entropy Pool in Unix systems). Suppose one day there was the coin function of God: int G ();
Because the god coins used here may not be uniform. However, it is guaranteed that g () can return the probability of X-1,1-x to 0, where x is an unknown constant (and x is not equal to 0 or 1).
Please implement the objective function: int F (double p);
Requirements
-
- The F function returns 1 with probability p and returns 0 with 1-p.
-
- Any library functions that are not used except for G. PS: Define Macro UINT_MAX=0XFFFFFFFF
Based on the above-mentioned similar idea, please construct the function to find the approximate value of the following irrational numbers:
-
- Double Pi (); Pi Pi
-
- Double E (); The base e of the natural logarithm function.
Tip: As a simulation process, the maximum number of repetitions can be introduced, please describe the idea and complete the code.
Ideas:
- Generated by the G () equal probability random number generation function, can refer to the introduction of the algorithm or this blog
- The number of times ( for example, 10 times ) is random by an equal-to-random function, and 1024 results are generated, and each structure is equal. Then we can analyze each random result, each random result can be expressed in decimal, for example:
Can be expressed in decimal 331, all possible decimal in the [0, 1024) range. So as long as the generated decimal number is less than 1024*p returns 1, greater than the return 0, so that the requirements can be met.
#include <stdlib.h>#include <iostream>using namespace STD;intFDoubleP) {intsum =0;intt =Ten;intall =1024x768;intT1 = all * p; for(inti =0; I < T; ++i) sum + = U () <<i;if(Sum < T1)return 1;Else if(Sum >= t1)return 0;}//Generate the uniform random function//reference book: <<algorithm introduction>>intU () {intN1 =-1, N2 =-1; Do{n1 = G (); N2 = G ();if(N1 = =0&& N2 = =1)return 1;Else if(N1 =1&& N2 = =0)return 0; } while(N1 = =0&& N2 = =0) || (N1 = =1&& N2 = =1))Exit(-1);}
2015 Ali Internship Line PEN Question-additional question 1