• Support PF! Buy your school textbooks, materials and every day products Here!

Writing a method of integration using the Monte Carlo method.

  • Thread starter r1z3
  • Start date
  • #1
2
0

Homework Statement


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).

The Attempt at a Solution


Code:
//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.

Homework Statement





Homework Equations





The Attempt at a Solution

 

Answers and Replies

  • #2
2
0
Never mind, solved it.
 

Related Threads on Writing a method of integration using the Monte Carlo method.

Replies
12
Views
918
  • Last Post
Replies
2
Views
1K
Replies
0
Views
950
  • Last Post
Replies
1
Views
882
Replies
4
Views
949
Replies
1
Views
2K
Replies
0
Views
972
Replies
0
Views
1K
Replies
0
Views
3K
Top