Assignment 11

Interpolation

by Jenni Meiklejohn

HTML

<center>
  <h3><div>Assignment 11</div><br>
   Interpolation</h3>

  <br>
  <br>
  <input type="number" id="hour" value="4.7">
  <input type="button" value="Enter" id="click" onclick="hour();">
  <br>
  <br>
  <div id="output"></div>

JavaScript

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

function hour() {
  var h = parseFloat(document.getElementById("hour").value);

  if (h >= 0.0 && h <= rainfall.length - 1) {
    document.getElementById("output").innerHTML = "Rainfall is " + interpolate(rainfall, h) + " at " + h + " hours";
  } else {
    document.getElementById("output").innerHTML = "Enter a number between 0 and 6";
  }
}

function interpolate(rainfall, h) {
  var a = Math.floor(h);
  var b = Math.floor(h + 1);
  var c = rainfall[Math.floor(h)];
  var d = rainfall[Math.floor(h + 1)];

  if (h == rainfall.length - 1) {
    return rainfall[h];
  } else {
    return Number((((h - a) * (d - c)) / (b - a)) + c).toFixed(3)
  }
}