我根据ernesto cesaros therom确定PI的价值。我在java中使用默认的随机方法。我将种子值设置为输入,它将确定它将生成多少对随机数。我总是得到2.4494附近的值
import java.util.Random;
import java.util.Scanner;
public class Projectone {
public static int count, sum = 0;
public static int a, b, gd;
public static void main(String[] args) {
// Enter seed number
Scanner kb = new Scanner(System.in);
System.out.print("Enter seed value: ");
int seed = kb.nextInt();
// Generate pairs of random numbers based on the seed number
Random rand = new Random();
for (int i = 0; i <= seed; i++) {
count++;
int a = rand.nextInt();
int b = rand.nextInt();
// Eliminating all negative numbers
if (a < 0) {
a *= -1;
}
if (b < 0) {
b *= -1;
}
// Entering random numbers into gcd
gd = gcd(a, b);
System.out.println("a = " + a + " b= " + b);
// breaks loop if gcd is =1 and adds the gcd
if (gd == 1)
break;
for (int j = 0; j <= seed; j++) {
sum += gd;
}
}
System.out.println("this is the count " + count);
if (sum == 0) {
sum = 1;
}
System.out.println("The sumation of the gcd's = " + sum);
//pluging in the values to the ceseros formula
float pi=(float) Math.sqrt(6.f*count/sum);
System.out.println("the ans is: "+pi);
}
public static int gcd(int a, int b) {
while (a != 0 && b != 0) {
int c = b;
b = a % b;
a = c;
}
return a + b;
}
}
此外,我想知道如何生成真正的随机数
答案 0 :(得分:1)
你应该编码定理所说的内容,即
两个随机数是互质的概率是6 / pi ^ 2
这是0.60792710185。
或另有说明
pi = sqrt(6 / found_probability)
因此
pi = sqrt(6 * tries / found_coprimes)
显然,你需要重复测试很多次才能获得合理的近似值。
现在,在您的代码中:
考虑以下代码:
private static int gcd(int a, int b) {
while (a != 0 && b != 0) {
int c = b;
b = a % b;
a = c;
}
return a + b;
}
public static void main(String[] args) {
Random random = new Random();
int iv = 1000000;
int coprime = 0;
for (int i = 0; i < iv; i++) {
int int1 = Math.abs(random.nextInt());
int int2 = Math.abs(random.nextInt());
if (gcd(int1, int2) == 1) {
coprime++;
}
}
System.out.println(Math.sqrt(6.0 * iv / coprime));
}
给出了像
这样的结果3.1425778292704583
关于你的第二个问题,标准&#34;随机&#34;数字生成器实际上是伪随机生成器。真正的随机数很难获得,请阅读True random generation in Java
答案 1 :(得分:0)
您的号码相对素数的概率是
P=number of pairs that are relatively prime/total number of pairs
基于此,您可以重新制定算法:
pi=Math.sqrt(6/P)
如果从0开始,你的循环不应该达到i&lt; = upperLimit;我&lt; UPPERLIMIT