I have a class Point, consisting of a point with x and y coordinates, and I have to write a method that computes and returns the equation of a straight line joi
Let's assume that we have the following points:
P0: ( x0 = 100, y0 = 240 )
P1: ( x1 = 400, y1 = 265 )
We can compute the coefficients of the line y = a*x + b that connects the two points using the polyfit method from numpy.
import numpy as np
import matplotlib.pyplot as plt
# Define the known points
x = [100, 400]
y = [240, 265]
# Calculate the coefficients. This line answers the initial question.
coefficients = np.polyfit(x, y, 1)
# Print the findings
print 'a =', coefficients[0]
print 'b =', coefficients[1]
# Let's compute the values of the line...
polynomial = np.poly1d(coefficients)
x_axis = np.linspace(0,500,100)
y_axis = polynomial(x_axis)
# ...and plot the points and the line
plt.plot(x_axis, y_axis)
plt.plot( x[0], y[0], 'go' )
plt.plot( x[1], y[1], 'go' )
plt.grid('on')
plt.show()
a = 0.0833333333333
b = 231.666666667
For installing numpy: http://docs.scipy.org/doc/numpy/user/install.html