Advertisement
caasinehc

Terms approximation

Nov 11th, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.     // Returns whether or not the given N is lower than the target
  3.     function tooLow(N) {
  4.         return (Math.log(N) + 1) / N >= 0.001;
  5.     }
  6.    
  7.     // Track a lower and upper bound, and squeeze them together
  8.     let lower = 0;
  9.     let upper = 1;
  10.    
  11.     // Seek an upper bound
  12.     while(tooLow(upper)) {
  13.         // If we aren't there yet, go bigger!
  14.         upper *= 2;
  15.        
  16.         // Log the new bounds
  17.         console.log(`${lower} < N < ${upper}`);
  18.     }
  19.  
  20.     // We've found an upper bound!
  21.     console.log("Upper bound found!");
  22.    
  23.     // Close in on the value
  24.     while(upper - lower > 1) {
  25.         // Make a guess as a new bound
  26.         let guess = Math.round((upper + lower) / 2);
  27.        
  28.         // Tighten the bounds
  29.         if(tooLow(guess)) lower = guess;
  30.         else              upper = guess;
  31.        
  32.         // Log the new bounds
  33.         console.log(`${lower} < N < ${upper}`);
  34.     }
  35.    
  36.     // All set!
  37.     console.log("Done!");
  38. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement