xxxxxxxxxx
49
/*
As part of a modeling problem, I've asked a student to
determine the value of t such that y = 20 * 10^t = 1000.
The answer tells us when to set an expiration date
so that a bacteria population does not exceed 1000
colony forming units.
Since this student does not yet know about logarithms, we're
using the bisection method to automate the trial and error
process.
Some possible improvements:
0. Introduce a parameter for max iterations, in case something
goes wrong.
1. Define y as a function at the top (defined so that
algorithm provides a zero of the function).
2. Handle y === 0 separately from y < 0, y > 0.
3. Define a bisect function that performs the algorithm,
with min, max, and y as parameters, and tolerance as a
parameter with a default value.
4. Compare algorithm to, e.g.
https://en.wikipedia.org/wiki/Bisection_method
https://www.geeksforgeeks.org/program-for-bisection-method/
5. Produce friendlier output using strings.
6. Accept user input through a GUI.
*/
let tMin = 1; // minimum value of t in search space
let tMax = 2; // maximum value of t in search space
let midpoint; // midpoint of search space
let population;
let tolerance = 0.1;
while (tMax - tMin > tolerance) {
midpoint = (tMin + tMax) / 2;
population = 20 * (10 ** midpoint);
if (population < 1000) { // midpoint is too small
tMin = midpoint; // make midpoint the new minimum
}
else { // midpoint is too big (or it's correct)
tMax = midpoint; // make midpoint the new maximum
}
}
console.log(tMin); //lower bound is safest as expiration date
console.log(tMax - tMin); //error does not exceed this value
console.log(20 * (10 ** tMin)); //population at time tMin
console.log(20 * (10 ** tMax)); //population at time tMax