mardi 1 mars 2016

Finding the area underneath y = x^4 in the domain 2 ≤ x ≤ 4 by using a Monte Carlo Method

In my approach, I will use a hypothetical rectangle with co-ordinates (2,0) , (4,0), (2, 256) and (4, 256). I will generate random xy co-ordinates within this rectangle and find the ratio between the number of co-ordinates that fall within the region defined by y ≤ x^4 and the number of co-ordinates that fall within the entire rectangle. Multiplying this by the area of the rectangle should give me the area under the graph.

I am struggling to generate random decimal xy co-ordinates in the defined rectangle. Any help would be much appreciated :)

I have only just started integration in school so my knowledge in this area is quite narrow as of now.

Here is my code:

public class IntegralOfX2 {

    public static double randDouble(double min, double max) {
        min = 2;
        max = 4;
        Random rand = new Random();
           double randomNum;
        randomNum = min + rand.nextDouble((max - min) + 1); // an error keeps occuring here

        return randomNum;
    }



    public static void main(String[] args) {

        double x = 0; // x co-ordinate of dart
        double y = 0; // y co-ordinate of dart
        int total_darts = 0; // the total number of darts
        int success_darts = 0; // the number of successful darts
        double xmax = 4;
        double xmin = 2;
        double ymax = 256;
        double ymin = 0;
        double area = 0;


        for (int i = 0; i < 400000000; i++) {
         //   x = randDouble(xmin, xmax);
         //   y = randDouble(ymin, ymax);


          x = xmin + (Math.random() * ((xmax - xmin) + 1));
          y = ymin + (Math.random() * ((ymax - ymin) + 1));

                    total_darts++;


            if (y <= (x * x * x * x)) {
                success_darts++;
            }

        }


       double ratio = (double)success_darts/(double)total_darts;
       area = ratio * 512;
       System.out.println(area);

    }
}




Aucun commentaire:

Enregistrer un commentaire