I am brand new at coding and I am currently working on creating a program that calculates the slope-intercept form of a line and information like the x-intercept and y-intercept of that line originating from the values of any two random coordinate pairs for example (x1,y1), (x2,y2) = (1,2), (3,4) what this presents as in matplotlib, when plotted is a line segment with a calculated slope (happens to be 1 here y = 1x + 1) that doesn't cross any axis'. I would like to draw another line over it with the same slope as the line segment that is continuous, to show where the line segment would cross the x and y-axis, but I want to do this for any combination of random coordinate pairs input by the user. I would also like to set the graph to load with the origin of the graph (0,0) at the bottom left in the frame when it is produced and not have the graph centered around my line segment when it is produced. Any help is much appreciated.
import numpy as np
import math
x1 = float(input("Enter a x coordinate for x1: "))
y1 = float(input("Enter a y coordinate for y1: "))
x2 = float(input("Enter a x coordinate for x2: "))
y2 = float(input("Enter a y coordinate for y2: "))
m = (y2-y1)/(x2-x1)
d = math.sqrt((x2 - x1)**2 + (y2-y1)**2)
slope_multiplied_by_negative_x1 = m * (-1 * x1)
b = float(y1) + float(slope_multiplied_by_negative_x1)
b_absolute = abs(b)
result = "y = " + (str(m) + "x " if m != 0 else "")
if m == 0:
sign = ""
elif b == 0:
sign = ""
elif b > 0:
sign = "+ "
else:
sign = "- "
try: X_intercept = float((-1 * b)/m)
except ZeroDivisionError:
X_intercept = 'n/a'
print(result + sign + ("" if b == 0 else (str(b_absolute))))
print("X intercept: " + ("0.0" if X_intercept == 0 else str(X_intercept)))
print("Y intercept: " + str(b))
print("Distance between (x1,y1) and (x2,y2): " + str(d))
x = [x1,x2]
y=[y1,y2]
t = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
plt.plot(x, y, color='c', linestyle='-', marker='o')
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.grid()
plt.show()
Segment with end points
(x1,y1), (x2,y2)
belongs to line with equationAt first we need to check extra cases of vertical and horizontal lines:
Otherwise, to find intersections with axes, we can just substitute
y=0
orx=0
to this equation.P.S. Note that you rarely need slope in computational geometry - there is a lot of more general approaches for line definition (described one, parametric method, theta-rho method)