public class JiFen {
public static void main(String[] args){
int N = 1000000;
int count = 0;
for(int i = 0; i < N; i++){
double x = Math.random();
double y = Math.random();
if(f(x) >= y)
count++;
}
System.out.println((double)count/N);
}
private static double f(double x) {
return x*x;
}
}
输出:0.333302
public class JiFen_toudian2 {
public static void main(String[] args){
double a = 0;
double b = 1;
double area = getArea(a,b);
System.out.println(area);
}
public static double getArea(double a, double b){
int sign = 1;//正负号标志位
if(a > b){
double t = a;
a = b;
b = t;
sign = -1;
}
int N = 10000;
double sum = 0;
for(int i = 0; i < N; i++){
double x = a + (b-a)*Math.random();//随机生成1个在(a,b)范围内的点
sum += f(x);
}
return (sum * (b-a)/N) * sign;
}
private static double f(double x) {
return x*x;
}
}
输出:0.33966325465503505
public class JiFen3 {
/**
* @param args
*/
public static void main(String[] args) {
double a;
double b;
double y;
a = 0;
b = 1;
y = getArea(a, b);
System.out.println(y);
}
static double f(double x){
return x*x;
}
static double getArea(double a, double b){
int sign = 1;
if(a > b){
double t = a;
a = b;
b = t;
sign = -1;
}
double h;
double x;
double sum = 0;
int n = 10000;
h = Math.abs(a - b)/n;
x = a;
for(int i = 0; i < n; i++){
sum += f(x) + f(x + h);
x = x + h;
}
return sum * h / 2 * sign;
}
}
输出:0.3333333349999429
public class Jifen_bianchang {
static double e = 0.00001;// 误差
public static void main(String[] args) {
double a = 0;// 积分下限
double b = 1;// 积分上限
double area = getArea(a, b);
System.out.println(area);
}
public static double getArea(double a, double b) {
int sign = 1;// 正负标志位
if (a > b) {
double t = a;
a = b;
b = t;
sign = -1;
}
double s1 = 0;// 前一个面积和
double s2 = 0;// 后一个面积和
double h = b - a;
s2 = getOneArea(a, b, h);
for (int i = 2; Math.abs(s1 - s2) > e; i *= 2) {
double t = h / i;// 每个梯形高
double sum = 0;
double x = a;
for (int j = 0; j < i; j++) {// 求梯形和
sum += getOneArea(x, x + t, t);
x = x + t;
}
s1 = s2;
s2 = sum;
}
return sign * s2;
}
public static double getOneArea(double a, double b, double h) {
return (f(a) + f(b)) * h / 2;
}
public static double f(double x) {
return x * x;
}
}
==================================================================================================
作者:nash_ 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:http://blog.csdn.net/nash_/article/details/8560759
===================================================================================================