proc triangle'area coords { foreach {xa ya xb yb xc yc} $coords break set a [expr {hypot($yb-$yc, $xb-$xc)}] set b [expr {hypot($ya-$yc, $xa-$xc)}] set c [expr {hypot($ya-$yb, $xa-$xb)}] set s [expr {($a+$b+$c)/2.}] expr {sqrt($s*($s-$a)*($s-$b)*($s-$c))} ;# Heronic formula }if 0 {For the general polygon I devised this recursive approach, which de facto does a triangulation, by measuring the area between the first three points, and then calling itself with the second corner's coordinates removed from the list: }
proc polygon::area coords { expr { [llength $coords]<6? 0 : [triangle'area [lrange $coords 0 5]] + [area [lreplace $coords 2 3]] } }if 0 { KBK 2004-07-23: Theres a shorter bit of code that calculates the area of a polygon, using the Trapezoid Rule rather than Heron' formula: }
proc parea { poly } { set xprev [lindex $poly end-1] set yprev [lindex $poly end] set area 0 foreach { x y } $poly { set area [expr { $area + ( ($x - $xprev) * ( $y + $yprev) ) }] set xprev $x; set yprev $y } return [expr { abs( $area / 2. ) }] }This is a general formula for the area of any polygon; it does not depend on triangles as a special case. It depends on the polygon's being simple: that is, dividing the plane into regions with winding numbers of zero and one. If a polygon intersects itself, each region of the polygon will contribute to the result a figure of the region's area times its winding number.KPV 2018-03-12: This formula is also known as the Shoelace formula.
See also: