- #1
r1z3
- 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.