Writing a method of integration using the Monte Carlo method.

Click For Summary
SUMMARY

The discussion focuses on implementing the Monte Carlo method in Java to integrate the function f(x) = x² from a = 1 to b = 2. The solution involves generating random points within a specified range and determining how many fall under the curve of the function. The final integration result is calculated using the formula (M / N) * M * (b - a), where M is the maximum y-value and N is the count of points under the curve. The user confirmed that their implementation was correct after initial doubts about the final equation.

PREREQUISITES
  • Java programming skills
  • Understanding of the Monte Carlo integration method
  • Familiarity with mathematical functions and their graphical representation
  • Basic knowledge of random number generation in programming
NEXT STEPS
  • Explore advanced Monte Carlo methods for higher-dimensional integration
  • Learn about error analysis in Monte Carlo simulations
  • Investigate alternative numerical integration techniques, such as Simpson's Rule
  • Study performance optimization techniques for Java applications
USEFUL FOR

Students learning numerical methods, Java developers implementing mathematical algorithms, and anyone interested in computational integration techniques.

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 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
1
Views
1K
  • · Replies 3 ·
Replies
3
Views
3K