We help IT Professionals succeed at work.

# Algorithm to Calculate the area of a 2D polygon

on
Medium Priority
697 Views
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.
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
|(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|

Commented:
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;

}

}
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
area = area + (xVals[i]*yVals[(i+1)%xVals.length])-(xVals[(i+1)%xVals.length]*yVals[i]);

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
Thank you very much for that.

Is'nt the formula you've implemented using the following rhetoric:

http://mathworld.wolfram.com/PolygonArea.html

?

CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
Yes.
Access more of Experts Exchange with a free account
##### Thanks for using Experts Exchange.

Limited access with a free account allows you to:

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile