Linear Function: y = mx + b (2 points given) in code
Categories:
Calculating a Linear Function (y = mx + b) from Two Points in C#

Learn how to derive the slope (m) and y-intercept (b) of a linear equation given two distinct points, and implement it in C#.
Linear functions are fundamental in mathematics and programming, representing a straight line on a graph. The standard form is y = mx + b
, where m
is the slope and b
is the y-intercept. Often, you'll be given two points (x1, y1)
and (x2, y2)
and need to determine the equation of the line passing through them. This article will guide you through the mathematical derivation and provide a C# implementation to solve this common problem.
Understanding the Math: Slope and Y-Intercept
Before diving into code, it's crucial to understand the underlying mathematical principles. Given two points P1(x1, y1)
and P2(x2, y2)
:
Calculate the Slope (m): The slope represents the rate of change of
y
with respect tox
. It's calculated as the 'rise' over the 'run':m = (y2 - y1) / (x2 - x1)
A critical condition here is that
x1
must not be equal tox2
. Ifx1 = x2
, the line is vertical, and the slope is undefined.Calculate the Y-intercept (b): Once you have the slope
m
, you can use either of the two given points(x1, y1)
or(x2, y2)
to find the y-interceptb
. Substitute the values into the linear equationy = mx + b
and solve forb
:y1 = m * x1 + b
b = y1 - m * x1
Alternatively, using the second point:
y2 = m * x2 + b
b = y2 - m * x2
Both methods will yield the same b
value, assuming m
is calculated correctly.
flowchart TD A["Start: Given P1(x1, y1) and P2(x2, y2)"] --> B{Is x1 == x2?} B -- Yes --> C["Error: Vertical Line (Slope Undefined)"] B -- No --> D["Calculate Slope (m):\nm = (y2 - y1) / (x2 - x1)"] D --> E["Calculate Y-intercept (b):\nb = y1 - m * x1"] E --> F["Result: y = mx + b"] C --> G[End] F --> G[End]
Flowchart for deriving a linear function from two points.
C# Implementation
Now, let's translate these mathematical steps into a C# code structure. We'll create a LinearFunction
class to encapsulate the slope and y-intercept, and a method to calculate these values from two Point
objects.
using System;
public struct Point
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
}
public class LinearFunction
{
public double Slope { get; private set; } // m
public double YIntercept { get; private set; } // b
public bool IsVertical { get; private set; }
public LinearFunction(Point p1, Point p2)
{
// Check for vertical line
if (p1.X == p2.X)
{
IsVertical = true;
Slope = double.NaN; // Slope is undefined for vertical lines
YIntercept = double.NaN; // Y-intercept is undefined (unless x=0)
return;
}
IsVertical = false;
Slope = (p2.Y - p1.Y) / (p2.X - p1.X);
YIntercept = p1.Y - Slope * p1.X;
}
public double CalculateY(double x)
{
if (IsVertical)
{
throw new InvalidOperationException("Cannot calculate Y for a vertical line.");
}
return Slope * x + YIntercept;
}
public override string ToString()
{
if (IsVertical)
{
return $"Vertical Line: x = {YIntercept}"; // YIntercept here stores the X-value for vertical lines
}
return $"y = {Slope:F2}x + {YIntercept:F2}";
}
}
public class Program
{
public static void Main(string[] args)
{
// Example 1: Standard line
Point pA = new Point(1, 2);
Point pB = new Point(3, 6);
LinearFunction func1 = new LinearFunction(pA, pB);
Console.WriteLine($"Points ({pA.X},{pA.Y}) and ({pB.X},{pB.Y}): {func1}");
Console.WriteLine($"Y at x=5: {func1.CalculateY(5):F2}\n");
// Example 2: Horizontal line
Point pC = new Point(0, 5);
Point pD = new Point(4, 5);
LinearFunction func2 = new LinearFunction(pC, pD);
Console.WriteLine($"Points ({pC.X},{pC.Y}) and ({pD.X},{pD.Y}): {func2}");
Console.WriteLine($"Y at x=10: {func2.CalculateY(10):F2}\n");
// Example 3: Vertical line
Point pE = new Point(2, 1);
Point pF = new Point(2, 7);
LinearFunction func3 = new LinearFunction(pE, pF);
Console.WriteLine($"Points ({pE.X},{pE.Y}) and ({pF.X},{pF.Y}): {func3}");
try
{
Console.WriteLine($"Y at x=2: {func3.CalculateY(2):F2}");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
C# code for calculating linear function parameters from two points.
x1 = x2
), the slope is undefined. In our LinearFunction
class, we handle this by setting IsVertical
to true
and Slope
to double.NaN
. The YIntercept
for a vertical line is also typically considered undefined, though sometimes the x
-value itself is used to define the line (e.g., x = 2
). Our ToString()
method reflects this for vertical lines.Testing the Implementation
To ensure our LinearFunction
class works correctly, consider various scenarios:
- Standard Line: Two distinct points forming a non-vertical, non-horizontal line.
- Horizontal Line: Two points with the same
y
coordinate (e.g.,(0, 5)
and(4, 5)
). The slope should be0
. - Vertical Line: Two points with the same
x
coordinate (e.g.,(2, 1)
and(2, 7)
). TheIsVertical
flag should betrue
, and attempts to calculateY
should throw an exception.
The Main
method in the provided code demonstrates these test cases.
By following these steps and using the provided C# code, you can reliably determine the equation of a linear function given any two points, handling edge cases like vertical lines gracefully.