## 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`

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```

```   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```

DevonMcCormick/SignedArea (last edited 2012-12-02 19:38:06 by DevonMcCormick)