PDA

Click to See Complete Forum and Search --> : VB Snippet - Math - Algorithm for the area of any polygon


krtxmrtz
Mar 3rd, 2003, 04:55 AM
Public Function Area(xpoly, ypoly, npoly)

'***********************************************************************
'Calculates the area of a closed contour (polygon) of any shape
'defined by xpoly(i),ypoly(i) with i=1,2,...,npoly
'The last point must close the contour, i.e.
'xpoly(1)=xpoly(npoly) & ypoly(1)=ypoly(npoly)
'Minimum npoly is 4 (i.e. a triangle)
'***********************************************************************
Dim a As Single

'Check for minimum num. of pts.
If npoly < 4 Then
Area = 0
Exit Function
End If

a = 0 'Initialize area
For i = 1 To npoly - 1
a = a + xpoly(i) * (ypoly(i + 1) - ypoly(i)) - ypoly(i) * (xpoly(i + 1) - xpoly(i))
Next

Area = 0.5 * a
End Function

krtxmrtz
May 7th, 2003, 08:36 AM
I have found that this function I posted some time ago in the VB code bank for area calculations was wrong and returned incorrect results (in some cases).
I thought it was working fine when I first checked it because the inaccuracies were small and thus difficult to spot for polygons with a large number of vertices, but then I found it failed in the most trivial cases.

I have re-edited the post and rewritten the code. Now the function is much simpler (and hopefully correct). I apologize for any inconveniences.

MartinLiss
May 7th, 2003, 10:07 AM
I took the liberty of combining your original thread and your correction notification.

krtxmrtz
May 7th, 2003, 11:24 AM
Ok thanks, now it makes more sense. Just wanted to make sure it didn't go unnoticed.