This calculator helps you determine the average rate (or average speed) when you have two different rates over two different periods. This is commonly used in physics and mathematics to understand scenarios where an object travels at varying speeds.
function calculateAverageRate() {
var rate1 = parseFloat(document.getElementById("rate1").value);
var time1 = parseFloat(document.getElementById("time1").value);
var rate2 = parseFloat(document.getElementById("rate2").value);
var time2 = parseFloat(document.getElementById("time2").value);
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = ""; // Clear previous results
if (isNaN(rate1) || isNaN(time1) || isNaN(rate2) || isNaN(time2)) {
resultDiv.innerHTML = "Please enter valid numbers for all fields.";
return;
}
if (time1 <= 0 || time2 <= 0) {
resultDiv.innerHTML = "Time values must be positive.";
return;
}
// Calculate distance for each part
var distance1 = rate1 * time1;
var distance2 = rate2 * time2;
// Calculate total distance and total time
var totalDistance = distance1 + distance2;
var totalTime = time1 + time2;
// Calculate average rate
var averageRate = totalDistance / totalTime;
// Display the result
resultDiv.innerHTML = "Distance covered at rate 1: " + distance1.toFixed(2) + " units" +
"Distance covered at rate 2: " + distance2.toFixed(2) + " units" +
"Total Distance: " + totalDistance.toFixed(2) + " units" +
"Total Time: " + totalTime.toFixed(2) + " time units" +
"Average Rate: " + averageRate.toFixed(2) + " units per time unit";
}
.calculator-container {
font-family: sans-serif;
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
max-width: 600px;
margin: 20px auto;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.calculator-container h2 {
text-align: center;
margin-bottom: 20px;
color: #333;
}
.inputs-section {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.input-group {
display: flex;
flex-direction: column;
}
.input-group label {
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
.input-group input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
button {
display: block;
width: 100%;
padding: 12px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 1.1rem;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
.result-section {
margin-top: 25px;
padding: 15px;
background-color: #e9ecef;
border: 1px solid #dee2e6;
border-radius: 4px;
text-align: center;
}
.result-section p {
margin: 8px 0;
font-size: 1.1rem;
}
.result-section strong {
color: #007bff;
}