Math question: How to compute the area of polygons

Jim Hurley jhurley at infostations.com
Fri Mar 21 12:48:00 EST 2003


>  Tomas Nally, P.E. on behalf of Tomas Nally, P.E. wrote:
    (snip)
>     > -- Now, going clockwise around the perimeter of the polygon,
>     > -- find the area of the virtual trapezoid under each line segment.
>     > -- A line segment is defined as the segment connecting
>     > -- the ith node and the (i + 1)th node.  Do this inside a
>     > -- counted loop.  In BASIC, a convenient loop for this is
>     > -- the For...Next loop.
>     >
>     > for i = 1 to (n - 1) -- note that I'm stopping at (n - 1)
>     >   x1 = x(i)
>     >   y1 = y(i)
>     >   x2 = x(i + 1)
>     >   y2 = y(i + 1)
>     >   trapArea(i) = y1 * (x2 - x1) + (1/2) * (x2 - x1) * (y2 - y1)
>     > next i
>     >
>     > -- This doesn't quite "close the loop" around the perimeter
>     > -- of the polygon.  In order to close the loop, we need to
>     > -- find the area under the line segment between the nth
>     > -- node and the very first node.
>     >
>     > x1 = x(n)
>     > y1 = y(n)
>     > x2 = x(1)
>     > y2 = y(1)
>     > trapArea(n) = y1 * (x2 - x1) + (1/2) * (x2 - x1) * (y2 - y1)
>     >
>     > -- Now, we have to add up all the areas of the elements
>     >
>     > TotalArea = 0
>     > for i = 1 to n
>     >   TotalArea = TotalArea + trapArea(i)
>     > next i
>     >
  (snip)


For anyone interested, this BASIC program is equivalent to the 
Transcript program I posted last Tuesday:

on mouseUp
    put field 1 into tList
    put 0 into area
    put  line 1 of tList into pOld
    repeat with i = 1 to the number of lines in tList
      put  line i of tList into  pNew
      add thisToArea(pNew,pOld) to area
      put pNew into pOld
    end repeat
    put area
end mouseUp

function thisToArea ptNew,ptOld
    put item 1 of ptNew into xNew
    put item 2 of ptNew into yNew
    put item 1 of ptOld into xOld
    put item 2 of ptOld into yOld
    return -(xNew - xOld)*(yNew + yOld)/2
end thisToArea

And it is also equivalent to the solution posted by Ray Griffith on 
the last installment of  this list, although his is more efficient 
and nifty as hell.

If anyone is interested, this method, sometimes call Newton's 
approximation, may be extended to calculate the  area  under any 
curve by treating the curve as a sequence of straight line segments 
(open polygon--so to speak). In effect it performs an integration. 
(When you have a curve which closes on itself, the integral under the 
closed curve is the *positive* area under the upper portion of the 
curve, plus the *negative*  area under the bottom portion of the 
curve. The difference is the area inside the  curve.)

I'm sure that last parenthetical statement is incomprehensible. But 
sometimes it is wiser to simply abandon hopeless projects rather than 
attempt redemption.

Jim



More information about the use-livecode mailing list