• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 683
  • Last Modified:

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.
0
stats786
Asked:
stats786
  • 3
  • 2
1 Solution
 
ozoCommented:
|(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|
0
 
stats786Author 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;


      }


}
0
 
ozoCommented:
area = area + (xVals[i]*yVals[(i+1)%xVals.length])-(xVals[(i+1)%xVals.length]*yVals[i]);
0
 
stats786Author Commented:
Thank you very much for that.

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

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


?



0
 
ozoCommented:
Yes.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now