以下算法适用于单维情况,但我想修改它以处理双积分。我怎么能这样做?
class doubleIntMonteCarlo
{
private static double f(double x)
{
return 1 / Math.pow( x , 2 );
}
public static double doubleIntMonteCarlo(double a, double b, int n)
{
double xSum = 0D, ySum = 0D, sum = 0D;
for (int i = 0; i < n; i++)
{
xSum = a + Math.random() * Math.abs( b - a );
sum += f(xSum);
}
return Math.abs( b - a ) * sum / n;
}
}
public class MonteCarloIntegration
{
public static void main(String[] args)
{
System.out.println(doubleIntMonteCarlo.doubleIntMonteCarlo(10, 250, 100000));
}
}
答案 0 :(得分:4)
试试这个:
public static double doubleIntMonteCarlo(double a, double b, double c, double d, int n)
{
double sum = 0D, xSum = 0D, ySum = 0D;
for (int i = 0; i < n; i++)
{
xSum = a + Math.random() * Math.abs(b - a);
ySum = c + Math.random() * Math.abs(d - c);
sum += f(xSum, ySum);
}
return Math.abs(b - a) * Math.abs(d - c) * sum / n;
}