The rate of change measures how a quantity changes over a specific period or interval. In mathematics and science, it's a fundamental concept used to describe how one variable changes in response to another. A common application is calculating the average rate of change of a function between two points.
function calculateRateOfChange() {
var initialValue = parseFloat(document.getElementById("initialValue").value);
var finalValue = parseFloat(document.getElementById("finalValue").value);
var initialPoint = parseFloat(document.getElementById("initialPoint").value);
var finalPoint = parseFloat(document.getElementById("finalPoint").value);
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = ""; // Clear previous results
if (isNaN(initialValue) || isNaN(finalValue) || isNaN(initialPoint) || isNaN(finalPoint)) {
resultDiv.innerHTML = "Please enter valid numbers for all fields.";
return;
}
if (initialPoint === finalPoint) {
resultDiv.innerHTML = "The initial point (x1) cannot be the same as the final point (x2) to avoid division by zero.";
return;
}
var changeInY = finalValue – initialValue;
var changeInX = finalPoint – initialPoint;
var rateOfChange = changeInY / changeInX;
resultDiv.innerHTML = "Change in Y (Δy): " + changeInY.toFixed(2) + "" +
"Change in X (Δx): " + changeInX.toFixed(2) + "" +
"Average Rate of Change: " + rateOfChange.toFixed(2) + "";
}
#rateOfChangeCalculator {
font-family: sans-serif;
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
max-width: 400px;
margin: 20px auto;
background-color: #f9f9f9;
}
#rateOfChangeCalculator h2 {
text-align: center;
margin-bottom: 20px;
color: #333;
}
.input-section {
margin-bottom: 15px;
}
.input-section label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
.input-section input {
width: calc(100% – 22px);
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
#rateOfChangeCalculator button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
#rateOfChangeCalculator button:hover {
background-color: #45a049;
}
#result {
margin-top: 20px;
padding: 15px;
border: 1px solid #eee;
background-color: #fff;
border-radius: 4px;
text-align: center;
}
#result p {
margin: 5px 0;
color: #333;
}