stats786
asked on
Algorithm to Calculate the area of a 2D polygon
I have two arrays, storing the x and y values of the polygon.
I wish to use these values to calculate the area of the polygon.
The polygon is a simple, concave 2d polygon.
Can someone possibly direct me to how I may achieve this.
Many Thanks.
I wish to use these values to calculate the area of the polygon.
The polygon is a simple, concave 2d polygon.
Can someone possibly direct me to how I may achieve this.
Many Thanks.
|(x[0]*y[1]-x[1]*y[0]+x[1] *y[2]-x[2] *y[1]+x[2] *y[3]-x[3] *y[2]+...+ x[n]*y[0]- x[0]*y[n]) /2|
ASKER
I tried implementing a quick test of what you suggested, but I don't get the values I expect. Can you spot what I'm doing wrong. Thanks.
import java.lang.Math.*;
public class areaTest
{
//Test Values
//square - expected area = 8
//static double[] polyX = { 1.0, 3.0, 3.0, 1.0, 1.0};
//static double[] polyY = { 1.0, 1.0, 3.0, 3.0, 1.0};
//triangle - expected area = 10.5
static double[] polyX = { 1.0, 4.0, 1.0, 1.0};
static double[] polyY = { 1.0, 4.0, 8.0, 1.0};
public static void main (String args[])
{
double test = calcArea(polyX, polyY);
System.out.println( test );
}
public static double calcArea(double xVals[],double yVals[])
{
int i;
double area = 0;
double mag;
for(i=0;i<xVals.length;i++ )
{
System.out.println(i);
//System.out.println(xVals [i]);
area = area + (xVals[i]*yVals[0])-(xVals [0]*yVals[ i]);
}
area = area/2;
mag= Math.abs(area);
return mag;
}
}
import java.lang.Math.*;
public class areaTest
{
//Test Values
//square - expected area = 8
//static double[] polyX = { 1.0, 3.0, 3.0, 1.0, 1.0};
//static double[] polyY = { 1.0, 1.0, 3.0, 3.0, 1.0};
//triangle - expected area = 10.5
static double[] polyX = { 1.0, 4.0, 1.0, 1.0};
static double[] polyY = { 1.0, 4.0, 8.0, 1.0};
public static void main (String args[])
{
double test = calcArea(polyX, polyY);
System.out.println( test );
}
public static double calcArea(double xVals[],double yVals[])
{
int i;
double area = 0;
double mag;
for(i=0;i<xVals.length;i++
{
System.out.println(i);
//System.out.println(xVals
area = area + (xVals[i]*yVals[0])-(xVals
}
area = area/2;
mag= Math.abs(area);
return mag;
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you very much for that.
Is'nt the formula you've implemented using the following rhetoric:
http://mathworld.wolfram.com/PolygonArea.html
?
Is'nt the formula you've implemented using the following rhetoric:
http://mathworld.wolfram.com/PolygonArea.html
?
Yes.