我试图用蒙特卡罗方法计算200边的多边形面积。我知道我的代码是正确的(这只是一个三角形的例子),但由于计算Math.cos函数时Java的错误,它非常不精确。有没有人知道如何修复它而不使用额外的类(我还没有研究面向对象的Java)?或者告诉我错误有多大?所以我不必在结尾处加上> 359的金额?非常感谢你的帮助...
import java.util.Random;
import java.util.Date;
import java.util.Scanner;
public class polygon {
public static void main(String args[]) {
Random ran = new Random();
Scanner a=new Scanner(System.in);
int side=3;
double dentro = 0;
double fuori = 0;
double x [] = {3,4,5};
double y [] = {1,6,3};
double lengthtopoint[]=new double [side];
double sidelength[]=new double [side];
double angles[]=new double [side];
for (int s =0; s< 1000000; s++){
double xcheck = ran.nextDouble()*10;
double ycheck = ran.nextDouble()*10;
for(int i=0;i<side;i++) {
lengthtopoint[i]=Math.sqrt(((x[i]-xcheck)*(x[i]-xcheck))+((y[i]-ycheck)*(y[i]-ycheck)));
}
for(int k=0;k<side-1;k++) {
sidelength[k]=Math.sqrt(((x[k+1]-x[k])*(x[k+1]-x[k]))+((y[k+1]-y[k])*(y[k+1]-y[k])));
}
sidelength[side-1]=Math.sqrt(((x[0]-x[side-1])*(x[0]-x[side-1]))+((y[0]-y[side-1])*(y[0]-y[side-1])));
for(int l=0;l<side-1;l++) {
angles[l] =((180/(Math.PI)))*Math.acos(((lengthtopoint[l]*lengthtopoint[l])+(lengthtopoint[l+1]*lengthtopoint[l+1])-(sidelength[l]*sidelength[l]))/(2*lengthtopoint[l]*lengthtopoint[l+1]));
}
angles[side-1] =((180/(Math.PI)))*Math.acos(((lengthtopoint[side-1]*lengthtopoint[side-1])+(lengthtopoint[0]*lengthtopoint[0])-(sidelength[side-1]*sidelength[side-1]))/(2*lengthtopoint[side-1]*lengthtopoint[0]));
double sum=0;
for(int m=0;m<side;m++) {
sum=sum+angles[m];
}
if (sum>359) {
dentro = dentro+1;
} else {
fuori = fuori + 1;
}
}
double Area = (dentro*100/(dentro+fuori));
System.out.println(Area);
}
}
答案 0 :(得分:0)
if (sum>359)
替换为if (sum > 180)
如果你以无限精度计算所有内容,你将获得一个k * 360形式的数字。如果你没有,那么你应该将它四舍五入到最接近的数字,可以被360整除。万一你得到程序认为358是0,但它也必须是360。