Javascript Array bisection(args)

Description

Javascript Array bisection(args)

/** bisection//  w w  w  . ja va2  s  .  c o m
 * Performs bisection on a function to return of one its zero on the given range.
 * @args  fct, range, maxIterations, stepSize, error  Object
 * @return   closest approximation to the zero of the function over the range
 */

var bisection = function(args) {
  
  var fct = args.fct,
    range = args.range,
    maxIterations = args.maxIterations,
    stepSize = args.stepSize,
    error = args.error;
  
  var val = {};
  
  var i = 0;
  
  while ( i < maxIterations ) {
    
    range.mid = ( ( range.min + range.max ) / 2.0 );
    
    val = {
      min: fct(range.min),
      mid: fct(range.mid),
      max: fct(range.max)
    };
    
    if ( Math.abs( ( val.max - val.min ) / 2 ) <= error ) break;
    
    ( ( val.min * val.mid ) > 0 ) ? range.min = range.mid : range.max = range.mid;
    
    i += stepSize;
    
  }
  
  return range.mid;
  
};



PreviousNext

Related