Bet you've never seen THIS in bash



  • ## Calculate the magnitude of a vector
    # For numbers which are close to forming a unit vector, the initial guess of
    # Mag^2/FIXEDPT is very close, and tends to converge in just 2-4 iterations.
    # Note that this only approximates sqrt, since I don't bother to round properly
    #
    # @param $1: x coordinate
    # @param $2: y coordinate
    # @param $3: z coordinate
    # @return $Result: the approximate magnitude of the vector
    #
    eval "Magnitude3D() {
            local magsq=$1*$1+$2*$2+$3*$3 mag=magsq/$FIXEDPT prevmag=0
            while((prevmag-mag>1||mag-prevmag>1));do((prevmag=mag,mag=(mag+magsq/mag)/2));done
            let Result=mag
    }"

    And, fyi, bash only has integer variables, so this is all done using fixed-point math.  ($FIXEDPT in this particular script is set to 1000).  The "eval" bit has the effect of "compiling" the constant of 1000 into the function, so that it doesn't get variable-expanded on each call.



  • That shows an ingenuity and balls of steel that not many programmers would commit to... however, that hardly excuses the fact that they're using bash to perform decimal calculations!! Why was this solution the best available? Where was bc?

    What kind of stripped down environment could this be running in that it didn't have any program with the facility to do non-integer arithmetic?


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.