lundi 6 février 2017

When using pseudo random numbers to estimate the value of pi I am getting a value around 2.44. What am I doing wrong?

I am determining the value of PI based on ernesto cesaros therom. I am using the default random method in java. I set the seed value as an input which will determine how many pairs of random numbers it will generate. I am always getting a value around 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;
     }
  }

Also I was wondering how to generate true random numbers




Aucun commentaire:

Enregistrer un commentaire