Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Monte carlo Intigration

  1. May 16, 2005 #1
    Dear friends

    I have been trying to write a code in Mathematica for solving a double integral with a non rectangular region through monte carlo integration, I have written a code that will solve for rectangular regions but i have no idea how to change it to work for non rectangular regions

    for example let the function be fun[x_,y_] := 2x
    what do i need to do to make this code to solve it for the non rectangular region {(x,y):y<=x<=4y,0<=y<=2}

    fun[x_,y_] := 2x
    a =
    b =
    c =
    d =

    nsamples=1000; nrepetitions=100;

    Print["For n=",nsamples," with ",nrepetitions," repetitions, \
    mean=",Mean[mc]," st.dev.=",StandardDeviation[mc]

    Please help
  2. jcsd
  3. May 16, 2005 #2
    You calculate the integral in the rectangular region, as you have done, but for the smaller domain, you need to check to see whether each (x,y) point is inside the smaller domain.

    The way I would do it would be to keep two running totals: the sum in the rectangular region(=sum), and the number of (x,y) points generated that are inside the smaller domain(=npass).

    The answer will then be: sum*npass/nsamples

    I'm not sure if this can be done without revamping your code. But I'm not a expert on the intracacies of Mathematica.
  4. May 17, 2005 #3


    User Avatar
    Science Advisor
    Homework Helper

    Thanks guys. It was very interesting and I learned a lot. This is what I came up with. I checked it against the integral of the indicated function over the specified domain. The integral is 40. The routine below returns 40.062.

    Code (Text):
    fun[x_,y_]:=2 x;
              If[yval<=xval && yval>=xval/4,
    Edit: Oh God. Should I not be doing this for Steve? You know Steve, I'm not sure this it right. Needs to be checked with other functions, other areas, perhaps optimized. It ran kind of slow. Don't use this for homework Ok?

    Edit2: Ok, the tlist needs to go outside of the first For loop. Nevermind Steve.
    Last edited: May 17, 2005
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?