Commits

Ivan Savov  committed a87b7e3

A nice numeric algo in js

  • Participants
  • Parent commits b3af029

Comments (0)

Files changed (1)

File lessons/math_in_javascript.js

+
+
+/*  To solve the equaiton fn(x)=0
+    we can start from two points x1 < x < x2 and 
+    search for the solution x by repeatedly bisecting       */
+
+var sign = function (x) { return x ? x < 0 ? -1 : 1 : 0; };
+
+var bisect_step = function (fn, x1, x2) {
+  var xm = (x1 + x2)/2;
+  // Return the sub-interval with
+  // oppositely-signed endpoints
+  if ( sign(fn(x1)) != sign(fn(xm)) ) {
+    return {left:x1, right:xm};
+  } else {
+    return {left:xm, right:x2};
+  }
+};
+
+var solve_bisect = function (fn, x1, x2) {
+  // assert( sign(fn(x1)) != sign(fn(x2)) );
+  // Stop when the mean of the endpoints
+  // is equal to one of the endpoints
+  while ( (x1 < (x1 + x2)/2) && ( (x1 + x2)/2 < x2 ) ){
+    interval = bisect_step(fn, x1, x2);
+    x1 = interval.left;
+    x2 = interval.right;
+  };
+  return x1;
+};
+
+
+