mardi 21 mars 2017

math.random in loop generating same number

I am trying to replicate a monte carlo simulation by finding the ratio of square vs circle when a randomly generated point of x and y is given between -1 and 1. I am having problem generating random numbers for x and y, because they return the same value for every loop.

import java.util.Scanner;

public class monte
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int loop_n = input.nextInt();

        //true false switch for the while loop
        boolean t_f = true;

        int count = 0;                  //counts how many iterations until inside the circle
        double radius = 0;              //calculates the pythagoras c from x, y coordinates
        double x = 0, y = 0;

        int i;
        for (i = 0; i < loop_n; i++)
        {

            while(t_f)                  //while loop to see if the c from x,y coordinates is smaller than 1
            {
                x = -1 + (Math.random() * (2));
                y = -1 + (Math.random() * (2));
                radius = Math.pow((Math.pow(x, 2.0)) + Math.pow(y, 2.0), 0.5);

                if (radius < 1)         //terminates while loop if radius is smaller than 1
                {                       //thus being inside the circle
                    t_f = false;
                }
                count++;
            }
            System.out.println("" + radius);
            System.out.println("" + count);
        }
    }
}

result from cmd

Is there a certain rule with Math.Random inside loops? Or am i writing my code wrong? I read s




Aucun commentaire:

Enregistrer un commentaire