Assignment #11 - Interpolation

by Mike Kerney

HTML

Please enter time you want to calulate the rainfall percentage for (Time must be a decimal between 0-6):
<br/>
<input type='text' id='input' value='0'>
<input type='button' value='Calculate Rainfall' onclick='calculate()'>
<div id='output'>
</div>

JavaScript

var RainArray = [0.00, 0.04, 0.11, 0.60, 0.87, 0.95, 1.00];

function clearDisplay() {
  var string = '';
  document.getElementById('output').innerHTML = string;
}

function calculate() {
  clearDisplay();
  var input = parseFloat(document.getElementById('input').value);

  if (input >= 0 && input <= 6) {
    var num1High = Math.floor(input);
    var num1Low = Math.ceil(input);
    if (num1High == num1Low) {
      document.getElementById('output').innerHTML = "Rainfall at " + input + " hours: " + parseFloat(RainArray[input] * 100) + "%";
      return;
    } else {
      var num2High = RainArray[num1High];
      var num2Low = RainArray[num1Low];
      var calc1 = parseFloat((num2Low - num2High) / (num1Low - num1High));
      var calc2 = parseFloat(num2Low - (calc1 * num1Low));
      var percent = parseFloat(((calc1 * input) + calc2) * 100);

      document.getElementById('output').innerHTML = "Rainfall at " + input + " hours: " + percent + "%";
    }
  } else {
    document.getElementById('output').innerHTML = "<br> Please enter a decimal time between 0 and 6. "
  }
}