Python Program to Find Intersection of Two Lines

Prompt

Program to find intersection of two lines
Python

Result

Certainly! Below is a Python program that calculates the intersection point of two lines, given their coefficients in the form of y = mx + c, where m is the slope and c is the y-intercept.

def find_intersection(m1, c1, m2, c2):
    """
    Calculate the intersection point of two lines given by the equations:
    y = m1*x + c1 and y = m2*x + c2.

    Parameters:
    m1 (float): Slope of the first line.
    c1 (float): Y-intercept of the first line.
    m2 (float): Slope of the second line.
    c2 (float): Y-intercept of the second line.

    Returns:
    tuple: A tuple (x, y) representing the intersection point, or None if the lines are parallel.
    """

    # Check if lines are parallel (slopes are equal)
    if m1 == m2:
        print("The lines are parallel and do not intersect.")
        return None

    # Calculate the x-coordinate of the intersection point
    x = (c2 - c1) / (m1 - m2)

    # Calculate the y-coordinate of the intersection point using the equation of the first line
    y = m1 * x + c1

    return (x, y)

# Example usage:
if __name__ == "__main__":
    # Coefficients for the first line (y = m1*x + c1)
    m1 = 2
    c1 = 3

    # Coefficients for the second line (y = m2*x + c2)
    m2 = -1
    c2 = 1

    # Find the intersection point
    intersection = find_intersection(m1, c1, m2, c2)

    # Print the result
    if intersection:
        print(f"The intersection point of the lines is: {intersection}")
Python

This program defines a function find_intersection that takes the slopes and y-intercepts of two lines as arguments and returns the intersection point as a tuple (x, y). If the lines are parallel (i.e., they have the same slope), the function prints a message and returns None. The example usage at the bottom demonstrates how to call the function with specific line coefficients and print the result.