num findRoot(MathFunction g, Interval i)

Source

num findRoot(MathFunction g, Interval i) {

  Expression tExpr = new IntervalLiteral(new Number(i.min), new Number(i.max));
  Variable t = new Variable('t');
  cm.bindVariable(t, tExpr);

  // Calculate value of the function at interval borders
  // G(i.min), G(i.max)
  Interval gEval = g.evaluate(EvaluationType.INTERVAL, cm);
  //Interval gEval = g.evaluate(i);

  // If interval contains 0, derive G(t)
  if (gEval.containsZero()) {
    MathFunction gDerived = g.derive('t');
    Interval gDerivedEval = gDerived.evaluate(EvaluationType.INTERVAL, cm);

    if (gDerivedEval.containsZero()) {
      // Monotonous part of function.
      // -> calculate root
      print(i);
      return _newtonRoot(g, gDerived, (i.min+i.max)/2.0);
    } else {
      // Recursively split.
      num r1 = findRoot(g, new Interval(i.min, (i.min+i.max)/2.0));
      num r2 = findRoot(g, new Interval((i.min+i.max)/2.0, i.max));
      return Math.min(r1,r2); // Return root ar minimal distance.
    }
  } else {
    // No root.
    // Return negative value for no hit.
//      return -1;
    return MAX_DIST;
  }
}