Faster hypot for JavaScript

When the distance between two points is required, one method of computation in modern browsers is a function called Hypot. Implementation of this function is often not optimized and ultimately calls on Math.sqrt at the last step. Performance tests indicate a calculation bottleneck with JavaScript's standard Math library implementation. Here then is an improvement of hypot at the cost of a fractional error (0.05%):

  function hypot(x, y) { // expects: abs(x) and abs(y)
    var a = Math.max(x,y),
        b = Math.min(x,y)/a,
        c = 1 + b*b;
    return a * ((-0.0705613450914645*c + 0.624084374908536)*c + 0.447383574908535);

Note, this function expects absolute values (which can be computed on the call). The formula in the return is a polynomial approximation of the square root of values in the range from 1 to 2. Caveat: your mileage may vary!

No comments :

Post a Comment

KVR News:

The Gadget Blog | Latest Gadgets, Technology