Slope Intercept Formula Calculator: Find Equation of a Line
:root {
–primary-color: #004a99;
–success-color: #28a745;
–background-color: #f8f9fa;
–text-color: #333;
–label-color: #555;
–border-color: #ccc;
–shadow-color: rgba(0, 0, 0, 0.1);
–white-color: #ffffff;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: var(–background-color);
color: var(–text-color);
line-height: 1.6;
margin: 0;
padding: 20px;
display: flex;
justify-content: center;
}
.main-container {
width: 100%;
max-width: 980px;
background-color: var(–white-color);
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 15px var(–shadow-color);
margin: 20px auto;
}
h1, h2, h3 {
color: var(–primary-color);
text-align: center;
margin-bottom: 20px;
}
h1 {
font-size: 2.2em;
}
h2 {
font-size: 1.8em;
margin-top: 40px;
}
h3 {
font-size: 1.4em;
margin-top: 30px;
}
.calculator-section {
background-color: var(–white-color);
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px var(–shadow-color);
margin-bottom: 40px;
}
.calculator-section h2 {
margin-top: 0;
}
.input-group {
margin-bottom: 25px;
text-align: left;
}
.input-group label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: var(–label-color);
font-size: 1.05em;
}
.input-group input[type="number"],
.input-group select {
width: calc(100% – 22px); /* Adjusted for padding and border */
padding: 12px;
border: 1px solid var(–border-color);
border-radius: 5px;
font-size: 1em;
box-sizing: border-box;
transition: border-color 0.3s ease;
}
.input-group input[type="number"]:focus,
.input-group select:focus {
border-color: var(–primary-color);
outline: none;
}
.input-group .helper-text {
font-size: 0.85em;
color: var(–label-color);
margin-top: 5px;
display: block;
}
.error-message {
color: #dc3545;
font-size: 0.85em;
margin-top: 8px;
display: none; /* Hidden by default */
text-align: left;
}
.button-group {
display: flex;
justify-content: space-between;
margin-top: 30px;
gap: 15px;
}
button {
padding: 12px 25px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
font-weight: bold;
transition: background-color 0.3s ease, transform 0.2s ease;
color: var(–white-color);
}
button.primary {
background-color: var(–primary-color);
}
button.primary:hover {
background-color: #003366;
transform: translateY(-2px);
}
button.secondary {
background-color: #6c757d;
}
button.secondary:hover {
background-color: #5a6268;
transform: translateY(-2px);
}
button.success {
background-color: var(–success-color);
}
button.success:hover {
background-color: #218838;
transform: translateY(-2px);
}
button:active {
transform: translateY(0);
}
.results-container {
margin-top: 30px;
padding: 25px;
background-color: #eef5ff; /* Light blue tint for results */
border-radius: 8px;
border: 1px dashed var(–primary-color);
}
.results-container h3 {
margin-top: 0;
color: var(–primary-color);
font-size: 1.6em;
border-bottom: 2px solid var(–primary-color);
padding-bottom: 10px;
text-align: center;
}
#mainResult {
font-size: 2.5em;
font-weight: bold;
color: var(–primary-color);
text-align: center;
margin: 15px 0;
display: block;
background-color: var(–white-color);
padding: 15px;
border-radius: 5px;
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
}
.intermediate-results div,
.formula-explanation div {
margin-bottom: 12px;
font-size: 1.1em;
color: #333;
}
.intermediate-results span,
.formula-explanation span {
font-weight: bold;
color: var(–primary-color);
}
.formula-explanation {
margin-top: 20px;
padding-top: 15px;
border-top: 1px solid #ddd;
font-size: 1.1em;
color: #444;
text-align: center;
}
.formula-explanation code {
background-color: #f0f0f0;
padding: 3px 6px;
border-radius: 3px;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 30px;
box-shadow: 0 2px 8px var(–shadow-color);
}
thead {
background-color: var(–primary-color);
color: var(–white-color);
}
th, td {
padding: 12px 15px;
text-align: center;
border: 1px solid #ddd;
}
tbody tr:nth-child(even) {
background-color: #f2f2f2;
}
caption {
caption-side: top;
font-weight: bold;
font-size: 1.2em;
color: var(–primary-color);
margin-bottom: 15px;
text-align: left;
}
canvas {
display: block;
margin: 30px auto;
max-width: 100%;
border: 1px solid var(–border-color);
border-radius: 5px;
background-color: var(–white-color);
}
.article-content {
margin-top: 40px;
text-align: left;
}
.article-content p,
.article-content ul,
.article-content ol {
margin-bottom: 20px;
}
.article-content li {
margin-bottom: 10px;
}
.article-content a {
color: var(–primary-color);
text-decoration: none;
font-weight: bold;
}
.article-content a:hover {
text-decoration: underline;
}
.faq-section {
margin-top: 40px;
padding-top: 30px;
border-top: 1px solid #eee;
}
.faq-section h2 {
text-align: left;
}
.faq-item {
margin-bottom: 20px;
border-left: 3px solid var(–primary-color);
padding-left: 15px;
}
.faq-item h3 {
margin-bottom: 5px;
text-align: left;
font-size: 1.2em;
color: var(–primary-color);
}
.faq-item p {
margin-bottom: 0;
color: #555;
}
#related-tools {
margin-top: 40px;
padding-top: 30px;
border-top: 1px solid #eee;
}
#related-tools h2 {
text-align: left;
}
#related-tools ul {
list-style: none;
padding: 0;
}
#related-tools li {
margin-bottom: 15px;
}
#related-tools a {
font-weight: bold;
font-size: 1.1em;
}
#related-tools span {
font-size: 0.95em;
color: #666;
display: block;
margin-top: 4px;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.main-container {
padding: 20px;
}
h1 {
font-size: 1.8em;
}
h2 {
font-size: 1.5em;
}
button.button-group {
flex-direction: column;
align-items: stretch;
}
button {
width: 100%;
}
#mainResult {
font-size: 2em;
}
}
Line Equation Calculator
y = mx + b
Formula: Slope m = (y2 - y1) / (x2 - x1). Then, find y-intercept b = y - mx using one point.
The slope intercept formula calculator is a powerful online tool designed to help you quickly determine the equation of a straight line when you have specific information about it. In mathematics, a line can be uniquely defined by its slope and its y-intercept. The most common and widely used form to represent this is the slope-intercept form: y = mx + b. This calculator makes finding this equation straightforward, whether you're working with two distinct points on the line or a single point and the line's slope.
This tool is invaluable for students learning algebra and calculus, engineers analyzing linear relationships, data scientists modeling trends, and anyone who needs to represent a straight-line relationship mathematically. It simplifies complex calculations, reducing the chance of manual errors and speeding up the process of line equation derivation.
Who Should Use the Slope Intercept Formula Calculator?
- Students: For homework, understanding linear functions, and preparing for exams.
- Teachers: To quickly generate examples and check student work.
- Engineers & Scientists: For modeling linear phenomena, analyzing data, and designing systems.
- Data Analysts: To identify linear trends in datasets and perform basic regressions.
- Mathematicians: As a quick reference or verification tool.
Common Misconceptions about the Slope-Intercept Form:
- Misconception 1: All lines can be written in slope-intercept form. Reality: Vertical lines (where x is constant) have an undefined slope and cannot be expressed in the
y = mx + b format. They are represented as x = c.
- Misconception 2: The 'b' value is always positive. Reality: The y-intercept 'b' can be positive, negative, or zero, depending on where the line crosses the y-axis.
- Misconception 3: The slope 'm' must be an integer. Reality: The slope can be any real number, including fractions and decimals.
The core of the {primary_keyword} lies in understanding the components of the slope-intercept equation: y = mx + b.
y and x represent the coordinates of any point on the line.
m represents the slope of the line.
b represents the y-intercept (the point where the line crosses the y-axis, i.e., where x=0).
Derivation Steps:
There are two primary methods to find m and b using this calculator:
Method 1: Using Two Points (x1, y1) and (x2, y2)
- Calculate the Slope (m): The slope measures the steepness of the line and is defined as the change in y divided by the change in x between two points.
m = (y2 - y1) / (x2 - x1)
Ensure that x2 - x1 is not zero. If it is, the line is vertical and cannot be expressed in slope-intercept form.
- Find the Y-Intercept (b): Once you have the slope (
m), you can use either of the given points (let's use (x1, y1)) and substitute the values into the slope-intercept equation:
y1 = m * x1 + b
Rearrange the equation to solve for b:
b = y1 - m * x1
- Write the Equation: Substitute the calculated values of
m and b back into the slope-intercept form: y = mx + b.
Method 2: Using a Point (xp, yp) and the Slope (m)
- Use the Slope-Intercept Form: You are given the slope (
m) directly. Substitute this value into the equation:
y = mx + b
- Solve for the Y-Intercept (b): Use the given point (xp, yp) and substitute its coordinates along with the slope
m into the equation:
yp = m * xp + b
Rearrange to solve for b:
b = yp - m * xp
- Write the Equation: Substitute the given
m and the calculated b into the slope-intercept form: y = mx + b.
Variables Used:
| Variable |
Meaning |
Unit |
Typical Range |
x1, y1 |
Coordinates of the first point |
Units of measurement (e.g., meters, dollars, abstract units) |
Any real number |
x2, y2 |
Coordinates of the second point |
Units of measurement |
Any real number |
xp, yp |
Coordinates of a single given point |
Units of measurement |
Any real number |
m |
Slope of the line |
Ratio (change in y / change in x) |
Any real number (except undefined for vertical lines) |
b |
Y-intercept |
Units of measurement (same as y-coordinate) |
Any real number |
y |
Dependent variable (vertical axis) |
Units of measurement |
Dependent on the line's equation |
x |
Independent variable (horizontal axis) |
Units of measurement |
Dependent on the line's equation |
Practical Examples (Real-World Use Cases)
Example 1: Calculating the Equation from Two Points
Suppose a delivery service charges a base fee plus a per-mile rate. You know that a 10-mile trip costs $25, and a 20-mile trip costs $40. You want to find the exact pricing structure (the equation of the line).
- Point 1: (x1, y1) = (10 miles, $25)
- Point 2: (x2, y2) = (20 miles, $40)
Calculations:
- Slope (m) = ($40 – $25) / (20 miles – 10 miles) = $15 / 10 miles = $1.50 per mile.
- Y-Intercept (b) = y1 – m * x1 = $25 – ($1.50/mile * 10 miles) = $25 – $15 = $10.
Result:
The equation of the line is y = 1.50x + 10. This means the base fee (y-intercept) is $10, and the charge per mile (slope) is $1.50.
Example 2: Finding the Equation Given a Point and Slope
Imagine you are analyzing the depreciation of a piece of equipment. You know that after 3 years, its value is $5000. You also know that the equipment depreciates linearly by $1000 per year.
- Point: (xp, yp) = (3 years, $5000)
- Slope: m = -$1000 per year (negative because it's depreciation)
Calculations:
- Y-Intercept (b) = yp – m * xp = $5000 – (-$1000/year * 3 years) = $5000 – (-$3000) = $5000 + $3000 = $8000.
Result:
The equation representing the value of the equipment over time is y = -1000x + 8000. This indicates the initial value (at year 0) was $8000, and it decreases by $1000 each year.
How to Use This {primary_keyword} Calculator
Using the {primary_keyword} Calculator is designed to be intuitive and efficient. Follow these simple steps:
- Select Calculation Method: Choose whether you will input 'Two Points' or a 'Point and Slope' from the dropdown menu.
- Input Your Data:
- If 'Two Points': Enter the x and y coordinates for both points (x1, y1 and x2, y2).
- If 'Point and Slope': Enter the x and y coordinates of the point (xp, yp), and then enter the slope (m). If you only have two points, you can leave the slope field blank, and the calculator will compute it.
- Observe Real-Time Results: As you enter valid numerical data, the calculator will instantly update the following:
- Slope (m): The calculated slope of the line.
- Y-Intercept (b): The calculated point where the line crosses the y-axis.
- Equation: The final equation of the line in the format
y = mx + b.
- Main Result: The complete equation displayed prominently.
- Handle Errors: If you enter non-numeric data, leave fields blank when required, or if
x1 = x2 (resulting in a vertical line), an error message will appear below the relevant input field. Correct the input to see the results update.
- Reset: Click the 'Reset' button to clear all fields and revert to default starting values.
- Copy Results: Click 'Copy Results' to copy the calculated slope, y-intercept, and the final equation to your clipboard for easy pasting elsewhere.
Reading and Interpreting Results:
The primary output is the equation y = mx + b. The value of m tells you how much y changes for every one-unit increase in x. A positive m means the line goes up from left to right; a negative m means it goes down. The value of b tells you the value of y when x is zero. This is often a starting point, baseline, or initial value in many real-world applications.
Decision-Making Guidance:
Use the derived equation to predict values. For instance, if y represents cost and x represents quantity, you can calculate the cost for any quantity. If y represents distance and x represents time, you can predict the distance traveled.
Key Factors That Affect {primary_keyword} Results
While the calculation itself is precise, the accuracy and relevance of the resulting line equation depend heavily on the input data and the context.
- Accuracy of Input Points/Slope: The most critical factor. If the coordinates of the points or the given slope are incorrect, the calculated line equation will be wrong. Ensure measurements or provided data are precise.
- Linearity Assumption: The slope-intercept form assumes a perfect linear relationship. Many real-world phenomena are non-linear (e.g., exponential growth, logistic curves). Applying a linear model to non-linear data will lead to inaccurate predictions outside the range of the input data.
- Data Range: The calculated line is most accurate within the range of the data used to determine it. Extrapolating far beyond this range can lead to significant errors, as the underlying relationship might change.
- Vertical Lines: A special case occurs when
x1 = x2. This defines a vertical line with an undefined slope, which cannot be represented in the y = mx + b form. The calculator handles this by indicating an error or specific condition.
- Units Consistency: Ensure that the units for the x and y coordinates are consistent. If you mix units (e.g., miles for x1 and kilometers for x2), the calculated slope and intercept will be meaningless.
- Noise in Data: In real-world data (like experimental measurements), there's often random 'noise' or error. Calculating a line from just two noisy points might not represent the underlying trend well. Techniques like linear regression (using more than two points) are better for noisy data.
- Contextual Relevance: Always consider if a linear model is appropriate for the situation. For example, while you can find a line through two points representing population growth, population growth is often exponential, making the linear model a simplification.
Frequently Asked Questions (FAQ)
Q1: What if my two points form a horizontal line?
A: If y1 = y2, the slope (m) will be 0. The equation will be in the form y = 0x + b, which simplifies to y = b. The calculator will correctly show m=0 and the corresponding y-intercept.
Q2: What if my two points form a vertical line?
A: If x1 = x2, the denominator (x2 – x1) becomes zero, making the slope undefined. This line cannot be represented in slope-intercept form (y=mx+b). Our calculator will indicate this or show an error message.
Q3: Can the slope (m) or y-intercept (b) be negative?
A: Yes, absolutely. A negative slope indicates a line that falls from left to right. A negative y-intercept means the line crosses the y-axis below the origin (at a negative y-value).
Q4: What does it mean if the slope is zero?
A: A slope of zero means the line is horizontal. The y-value remains constant regardless of the x-value. This represents a situation where there is no change in the dependent variable (y) with respect to the independent variable (x).
Q5: Can I use this calculator for non-linear equations?
A: No, this calculator is specifically designed for linear equations that can be expressed in the slope-intercept form (y = mx + b). It cannot handle curves or other non-linear relationships.
Q6: How accurate is the calculation?
A: The calculation itself is mathematically exact for the given inputs. However, the real-world accuracy depends entirely on the precision and appropriateness of the input data.
Q7: What if I have more than two points?
A: If you have more than two points and they don't fall perfectly on a single line (due to real-world noise or error), you would typically use linear regression techniques to find the "best-fit" line. This calculator finds the exact line through the two points provided or the line defined by a point and slope.
Q8: What is the difference between slope-intercept form and standard form (Ax + By = C)?
A: Slope-intercept form (y = mx + b) is useful for visualizing the line's slope and y-intercept. Standard form (Ax + By = C) is often used for its clean integer coefficients and ease in finding intercepts. You can convert between forms mathematically.
var calculationType = 'twoPoints';
var canvas = document.getElementById('lineChart');
var ctx = canvas.getContext('2d');
var myChart = null;
function toggleInputs() {
var type = document.getElementById('calculationType').value;
calculationType = type;
if (type === 'twoPoints') {
document.getElementById('twoPointsInputs').style.display = 'block';
document.getElementById('pointSlopeInputs').style.display = 'none';
} else {
document.getElementById('twoPointsInputs').style.display = 'none';
document.getElementById('pointSlopeInputs').style.display = 'block';
}
resetCalculator(); // Reset when switching types
}
function validateInput(value, id, errorId, allowNull = false) {
var errorElement = document.getElementById(errorId);
errorElement.style.display = 'none'; // Hide previous error
if (value === " && !allowNull) {
errorElement.textContent = 'This field cannot be empty.';
errorElement.style.display = 'block';
return false;
}
if (value !== " && isNaN(parseFloat(value))) {
errorElement.textContent = 'Please enter a valid number.';
errorElement.style.display = 'block';
return false;
}
if (value !== " && parseFloat(value) < 0 && id !== 'slopeInput') { // Allow negative slopes
errorElement.textContent = 'Value cannot be negative.';
errorElement.style.display = 'block';
return false;
}
if (value !== '' && id === 'slopeInput' && (parseFloat(value) === Infinity || parseFloat(value) === -Infinity) ) {
errorElement.textContent = 'Slope cannot be infinity.';
errorElement.style.display = 'block';
return false;
}
return true;
}
function calculateLine() {
var isValid = true;
var x1, y1, x2, y2, xp, yp, slopeVal;
var slope = null;
var yIntercept = null;
var equation = "y = mx + b";
if (calculationType === 'twoPoints') {
x1 = document.getElementById('x1').value;
y1 = document.getElementById('y1').value;
x2 = document.getElementById('x2').value;
y2 = document.getElementById('y2').value;
isValid &= validateInput(x1, 'x1', 'x1Error');
isValid &= validateInput(y1, 'y1', 'y1Error');
isValid &= validateInput(x2, 'x2', 'x2Error');
isValid &= validateInput(y2, 'y2', 'y2Error');
if (isValid) {
x1 = parseFloat(x1);
y1 = parseFloat(y1);
x2 = parseFloat(x2);
y2 = parseFloat(y2);
if (x1 === x2) {
document.getElementById('x1Error').textContent = 'x1 and x2 cannot be the same for a non-vertical line.';
document.getElementById('x1Error').style.display = 'block';
isValid = false;
} else {
slope = (y2 – y1) / (x2 – x1);
yIntercept = y1 – slope * x1;
}
}
} else { // pointSlope
xp = document.getElementById('xp').value;
yp = document.getElementById('yp').value;
slopeVal = document.getElementById('slopeInput').value;
isValid &= validateInput(xp, 'xp', 'xpError');
isValid &= validateInput(yp, 'yp', 'ypError');
if (slopeVal === '') {
document.getElementById('slopeInputError').textContent = 'Slope is required for this method.';
document.getElementById('slopeInputError').style.display = 'block';
isValid = false;
} else {
isValid &= validateInput(slopeVal, 'slopeInput', 'slopeInputError');
if (isValid) {
slope = parseFloat(slopeVal);
xp = parseFloat(xp);
yp = parseFloat(yp);
yIntercept = yp – slope * xp;
}
}
}
if (isValid && slope !== null && yIntercept !== null) {
var slopeFormatted = slope.toFixed(4).replace(/\.?0+$/, '');
var yInterceptFormatted = yIntercept.toFixed(4).replace(/\.?0+$/, '');
document.getElementById('slopeResult').innerHTML = 'Slope (m):
' + slopeFormatted + '';
document.getElementById('yInterceptResult').innerHTML = 'Y-Intercept (b):
' + yInterceptFormatted + '';
var equationString = "y = ";
if (slope !== 0) {
equationString += slopeFormatted + "x";
if (yIntercept > 0) {
equationString += " + " + yInterceptFormatted;
} else if (yIntercept < 0) {
equationString += " – " + Math.abs(yInterceptFormatted);
}
} else {
equationString += yInterceptFormatted;
}
if (slope === 0 && yIntercept === 0) {
equationString = "y = 0";
}
document.getElementById('equationResult').innerHTML = 'Equation:
' + equationString + '';
document.getElementById('mainResult').textContent = equationString;
updateChart(slope, yIntercept);
} else {
document.getElementById('slopeResult').innerHTML = 'Slope (m):
N/A';
document.getElementById('yInterceptResult').innerHTML = 'Y-Intercept (b):
N/A';
document.getElementById('equationResult').innerHTML = 'Equation:
N/A';
document.getElementById('mainResult').textContent = "y = mx + b";
clearChart();
}
}
function resetCalculator() {
document.getElementById('x1').value = ";
document.getElementById('y1').value = ";
document.getElementById('x2').value = ";
document.getElementById('y2').value = ";
document.getElementById('xp').value = ";
document.getElementById('yp').value = ";
document.getElementById('slopeInput').value = ";
var errorElements = document.querySelectorAll('.error-message');
for (var i = 0; i < errorElements.length; i++) {
errorElements[i].style.display = 'none';
}
document.getElementById('slopeResult').innerHTML = 'Slope (m):
N/A';
document.getElementById('yInterceptResult').innerHTML = 'Y-Intercept (b):
N/A';
document.getElementById('equationResult').innerHTML = 'Equation:
N/A';
document.getElementById('mainResult').textContent = "y = mx + b";
clearChart();
toggleInputs(); // Re-apply display logic based on current type
}
function copyResults() {
var mainResult = document.getElementById('mainResult').textContent;
var slopeText = document.getElementById('slopeResult').innerText.replace('Slope (m): ', ");
var yInterceptText = document.getElementById('yInterceptResult').innerText.replace('Y-Intercept (b): ', ");
var equationText = document.getElementById('equationResult').innerText.replace('Equation: ', ");
var textToCopy = "— Slope Intercept Formula Results —\n\n";
textToCopy += "Equation: " + mainResult + "\n";
textToCopy += "Slope (m): " + slopeText + "\n";
textToCopy += "Y-Intercept (b): " + yInterceptText + "\n";
textToCopy += "\nCalculated using: " + calculationType.replace(/([A-Z])/g, ' $1').trim() + "\n";
if (calculationType === 'twoPoints') {
textToCopy += "Point 1: (" + document.getElementById('x1').value + ", " + document.getElementById('y1').value + ")\n";
textToCopy += "Point 2: (" + document.getElementById('x2').value + ", " + document.getElementById('y2').value + ")\n";
} else {
textToCopy += "Point: (" + document.getElementById('xp').value + ", " + document.getElementById('yp').value + ")\n";
textToCopy += "Slope: " + document.getElementById('slopeInput').value + "\n";
}
var textArea = document.createElement("textarea");
textArea.value = textToCopy;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'Results copied!' : 'Failed to copy results.';
console.log(msg); // Or show a temporary notification to the user
// alert(msg); // Avoid using alert in production for better UX
} catch (err) {
console.log('Oops, unable to copy', err);
// alert('Failed to copy results.');
}
document.body.removeChild(textArea);
}
function clearChart() {
if (myChart) {
myChart.destroy();
myChart = null;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw axes if desired, or simply clear
}
function updateChart(slope, yIntercept) {
clearChart(); // Clear previous chart if any
if (slope === null || yIntercept === null || !isFinite(slope) || !isFinite(yIntercept)) {
ctx.fillText("Cannot draw chart with invalid slope or intercept.", canvas.width / 2, canvas.height / 2);
return;
}
var dataPoints = [];
var xRange = 10; // Default x range
var numPoints = 50; // Number of points for the line
// Adjust x-range based on y-intercept and slope to center the view
if (Math.abs(yIntercept) > 5) {
xRange = Math.abs(yIntercept) * 1.5;
}
if (Math.abs(slope) > 1) {
xRange = Math.max(xRange, Math.abs(yIntercept / slope) * 1.5);
}
xRange = Math.max(xRange, 10); // Ensure a minimum range
var maxX = xRange;
var minX = -xRange;
// Determine y-range based on slope and x-range
var maxY = Math.max(Math.abs(yIntercept) + Math.abs(slope) * xRange, 5);
var minY = -maxY;
// Add fixed points for axes lines
var xAxisY = canvas.height / 2;
var yAxisX = canvas.width / 2;
// Scale factors
var xScale = canvas.width / (2 * xRange);
var yScale = canvas.height / (2 * maxY);
// Draw X-axis
ctx.beginPath();
ctx.moveTo(0, xAxisY);
ctx.lineTo(canvas.width, xAxisY);
ctx.strokeStyle = '#ccc';
ctx.lineWidth = 1;
ctx.stroke();
// Draw Y-axis
ctx.beginPath();
ctx.moveTo(yAxisX, 0);
ctx.lineTo(yAxisX, canvas.height);
ctx.strokeStyle = '#ccc';
ctx.lineWidth = 1;
ctx.stroke();
// Add labels for axes
ctx.fillStyle = '#555′;
ctx.font = '12px Arial';
ctx.textAlign = 'right';
ctx.fillText('0', yAxisX – 5, xAxisY + 15); // Origin label
ctx.textAlign = 'center';
ctx.fillText('X', canvas.width – 15, xAxisY + 20);
ctx.fillText('Y', yAxisX + 15, 15);
// Draw the line itself
ctx.beginPath();
ctx.strokeStyle = 'var(–primary-color)';
ctx.lineWidth = 3;
for (var i = 0; i < numPoints; i++) {
var x = minX + (maxX – minX) * i / (numPoints – 1);
var y = slope * x + yIntercept;
// Convert to canvas coordinates
var canvasX = yAxisX + x * xScale;
var canvasY = xAxisY – y * yScale; // Invert Y for canvas
if (i === 0) {
ctx.moveTo(canvasX, canvasY);
} else {
ctx.lineTo(canvasX, canvasY);
}
}
ctx.stroke();
// Add legend/labels
ctx.fillStyle = '#333';
ctx.font = '14px Arial';
ctx.textAlign = 'left';
ctx.fillText('y = ' + slope.toFixed(2) + 'x + ' + yIntercept.toFixed(2), 20, 30);
ctx.fillText('Slope (m): ' + slope.toFixed(4).replace(/\.?0+$/, ''), 20, 55);
ctx.fillText('Y-Intercept (b): ' + yIntercept.toFixed(4).replace(/\.?0+$/, ''), 20, 80);
}
// Initial setup
window.onload = function() {
toggleInputs(); // Set initial display based on default selection
calculateLine(); // Perform initial calculation if defaults are set
};