1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Writing a method of integration using the Monte Carlo method.

  1. Sep 30, 2012 #1
    1. The problem statement, all variables and given/known data
    So the problem is to write a method/function in Java to integrate x2 from a = 1 to b = 2 using the Monte Carlo method. Basically:

    1. Generate random points in the range of (0, M) and domain of (a, b), where M is a y value greater than the maximum of f(x) = x2 within (a, b).

    2. For each point, determine whether or not it is within the area of f(x).

    3. Find the answer to (M / N) * M * (b - a), where N is the number of points that fell within the area of f(x).

    3. The attempt at a solution
    Code (Text):

    //Find maximum value of f(x) in (a, b)
    double a = 1;
    double b = 2;
    double M = 0;
    double y1 = 0;
    for(int x1 = (int)a;x1 <= b;x1++)
    {
        y1 = Math.pow(x1, 2);
        if(y1 > M)
        {
            M = y1;
        }
    }
    M += 10;
    //Generate points, check if under f(x)
    double[] x = new double[10000];
    double[] y = new double[10000];
    int N = 0;
    for(int i = 0;i < x.length;i++)
    {
        x[i] = Math.random() * (b - a) + a;
        y[i] = Math.random() * M;
        if(y[i] <= Math.pow(x[i], 2))
        {
            N++;
        }
    }
    System.out.println(M / N * M * (b-a));
     
    I feel like I did the coding right, but I'm not sure where I made an error nor if I copied the last equation (M / N *...) correctly from the board or not.
    1. The problem statement, all variables and given/known data



    2. Relevant equations



    3. The attempt at a solution
     
  2. jcsd
  3. Sep 30, 2012 #2
    Never mind, solved it.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Writing a method of integration using the Monte Carlo method.
  1. Monte-Carlo Method (Replies: 2)

Loading...