Version 3 of hypot

Updated 2003-05-21 19:41:38

Purpose: Discuss the math function hypot.


The call,

    [expr { hypot( $x, $y ) }]

returns the length of the hypotenuse of a right triangle when the length of the legs are $x and $y. It is equivalent to

    [expr { sqrt( $x * $x + $y * $y ) }]

except that it can handle cases where $x or $y are extremely large or extremely small without getting overflow or underflow.

In cases where there are no problems with being very close to the limits of the underlying double representation and you don't actually need the distance itself (e.g. in circle intersection testing and checking to see if one point is close enough to another) it is often quicker to work with the square of the length of the hypotenuse and avoid the expensive square root operation. I do not know how this ranks up with the additional overheads of math in Tcl though. DKF


The most common use of hypot is in Converting between rectangular and polar co-ordinates.


hypot is also available in Tclx.


GPS The hypotenuse is very useful for drawing lines pixel by pixel. For example:

 proc draw.line.on.image {img x1 y1 x2 y2 color} {
        set xDiff [expr {$x2 - $x1}]
        set yDiff [expr {$y2 - $y1}]

        set numPixels [expr {hypot($xDiff,$yDiff)}]
        set xRatio [expr {$xDiff / $numPixels}]
        set yRatio [expr {$yDiff / $numPixels}]

        for {set p 0} {$p < $numPixels} {incr p} {
                set x [expr {round($xRatio * $p) + $x1}]
                set y [expr {round($yRatio * $p) + $y1}]
                $img put $color -to $x $y [expr {$x + 1}] [expr {$y + 1}]
        }        
 }

 proc main {} {
        set img [image create photo -width 300 -height 300]
        draw.line.on.image $img 10 10 100 100 green
        draw.line.on.image $img 50 20 50 200 blue
        draw.line.on.image $img 40 50 300 50 maroon

        pack [label .l -image $img]
 }
 main 

Math function help - Arts and crafts of Tcl-Tk programming - Category Mathematics