The average rate of change of a function measures how much the function's output changes, on average, with respect to a change in its input over a given interval. It's essentially the slope of the secant line connecting two points on the function's graph.
function calculateAverageRateOfChange() {
var functionStr = document.getElementById("functionInput").value;
var x1Str = document.getElementById("x1").value;
var x2Str = document.getElementById("x2").value;
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = ""; // Clear previous results
// — Input Validation —
if (!functionStr || !x1Str || !x2Str) {
resultDiv.innerHTML = "Please fill in all fields.";
return;
}
var x1 = parseFloat(x1Str);
var x2 = parseFloat(x2Str);
if (isNaN(x1) || isNaN(x2)) {
resultDiv.innerHTML = "x1 and x2 must be valid numbers.";
return;
}
if (x1 === x2) {
resultDiv.innerHTML = "The interval cannot have the same starting and ending x-values (x1 must be different from x2).";
return;
}
// — Function Evaluation —
// A simple parser for basic polynomial functions (e.g., x^2 + 2x – 1)
// This is a simplified parser and may not handle all complex mathematical expressions.
function evaluateFunction(funcString, xValue) {
try {
// Replace 'x' with the specific value
var expression = funcString.replace(/x/g, `(${xValue})`);
// Evaluate the expression. For security, consider a more robust math parser
// for production environments that handle arbitrary input.
// For this example, we'll use eval with caution, assuming controlled input.
return eval(expression);
} catch (e) {
console.error("Error evaluating function:", e);
return NaN; // Return NaN if there's an error evaluating the function
}
}
var y1 = evaluateFunction(functionStr, x1);
var y2 = evaluateFunction(functionStr, x2);
if (isNaN(y1) || isNaN(y2)) {
resultDiv.innerHTML = "Could not evaluate the function for the given x-values. Please check your function input.";
return;
}
// — Calculation —
var deltaY = y2 – y1;
var deltaX = x2 – x1;
var averageRateOfChange = deltaY / deltaX;
// — Display Result —
resultDiv.innerHTML =
"Function: f(x) = " + functionStr + "" +
"Interval: [" + x1 + ", " + x2 + "]" +
"f(" + x1 + ") = " + y1.toFixed(4) + "" +
"f(" + x2 + ") = " + y2.toFixed(4) + "" +
"Change in y (Δy): " + deltaY.toFixed(4) + "" +
"Change in x (Δx): " + deltaX.toFixed(4) + "" +
"
Average Rate of Change: " + averageRateOfChange.toFixed(4) + "