User:Devon McCormick/SignedArea

From J Wiki
Jump to: navigation, search

Example of J Code to Calculate Signed Area

Here is some J code, based on the code found here, to calculate the “signed area” contained within a set of points. The concept of a "signed area" arises when we consider a set of points defining a polygon with regard to the order of the points. So the following set of points represents the "bowtie" shape shown below but with the upper part of the polygon drawn clockwise and the lower part drawn counter-clockwise.

   pts=. 0 0,_1 1,1 1,_1 _1,:1 _1
 0  0
_1  1
 1  1
_1 _1
 1 _1

In order to draw the full polygon, we need to replicate the first point-pair (the origin) at the end in order to complete the cycle, to draw the final line.

   (],[:{.]) pts
 0  0
_1  1
 1  1
_1 _1
 1 _1
 0  0

We use  j./ below to turn the coordinate pairs into complex numbers, a form understood by the "plot" function to represent two-dimensional points.

   'type line' plot j./|:(],[:{.]) pts    NB. Clockwise top + counter-clockwise bottom

SignedArea0plot-arrows.png

So, if we define the signed area verb as shown here to work with the two-column form, using what is known as the surveyor's formula for calculating area, the opposing directions of the halves of the polygon given them opposite signs, so their areas cancel out each other.

   areapts=: [:([: -:[: +/(0{]) * [:(1&|.-_1&|.) 1{]) |:

   areapts pts
0

However, if we change the order of the points as shown here, to draw both halves clockwise, both areas are negative and add up to negative two.

   ]pts1=. 0 0,_1 1,1 1,0 0,1 _1,_1 _1,:0 0
 0  0
_1  1
 1  1
 0  0
 1 _1
_1 _1
 0  0
   'type line' plot j./|:pts1              NB. Both parts clockwise

SignedArea2plot.Arrowspng.png

   areapts pts1
 _2

If we reverse the direction of this latter set of points, drawing both halves in a counterclockwise direction, the sign of the area is reversed accordingly.

   areapts |.pts1
2