Writing a method of integration using the Monte Carlo method.

AI Thread Summary
The discussion focuses on implementing a Monte Carlo method in Java to integrate the function f(x) = x² from a = 1 to b = 2. The approach involves generating random points within a defined range and checking if they fall under the curve of the function. The calculation for the area uses the formula (M / N) * M * (b - a), where M is a height limit and N is the number of points under the curve. The user initially expressed uncertainty about the code's correctness and the final equation but later confirmed they resolved the issue. The thread highlights the practical application of Monte Carlo integration in programming.
r1z3
Messages
2
Reaction score
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.
 
Physics news on Phys.org
Never mind, solved it.
 

Similar threads

Replies
2
Views
2K
Replies
2
Views
3K
Replies
12
Views
2K
Replies
1
Views
2K
Replies
1
Views
2K
Replies
1
Views
2K
Replies
2
Views
2K
Replies
3
Views
2K
Back
Top