参考网站:https://www.python-course.eu/dividing_lines_between_classes.php
接着上章到了一条直线分开了两个点,从数学的角度分析一下,直线为函数为y=mx+b,令位于直线上方的点为(x1,y1),位于直线下方的点为(x2,y2),则有
Δy1 = y1 - (m * x1 + b) > 0
Δy2 = y2 - (m * x2 + b) < 0
假设直线过原点,则b=0,整理一下总结就是:
如果点在线的上方:y1 - m * x1 > 0
如果点在线上:y1 - m * x1 = 0
如果点在线的下方:y1 - m * x1 < 0
通过上面的介绍,我们就知道了一条线能把两个点分开的数学表达,上篇我们选取m=1,通过肉眼我们知道这条线能把两个点分开,但是能将两个点分开的直线有无数条,通过上面的数学关系我们可以将这些直线识别出来。
import numpy as np
import matplotlib.pyplot as plt
import math
def judgement(m, c):
def delta_y(x, y):
delta = y - (m * x + c)
if delta == 0:
pos = 0
elif delta < 0:
pos = -1
else:
pos = 1
return (delta, pos)
return delta_y
point1 = (6, 2)
point2 = (2, 6)
points = [point1, point2]
fig, ax = plt.subplots()
print(fig,ax)
ax.set_xlabel("X")
ax.set_ylabel("Y")
x_min,x_max = -1,8
y_min,y_max = -1,8
ax.set_xlim([x_min, x_max])
ax.set_ylim([y_min, y_max])
X = np.arange(x_min, x_max, 0.1)
step = math.pi/2/20
for x in np.arange(0, math.pi/2+step, step):
m = np.tan(x)
# slope = x
judgement1 = judgement(m , 0)
Y = m * X
results = []
for point in points:
results.append(judgement1(*point))
if (results[0][1] != results[1][1]):
ax.plot(X, Y, "g-", linewidth=0.8, alpha=0.9)
else:
ax.plot(X, Y, "r-", linewidth=0.8, alpha=0.9)
size = 10
for (index, (x, y)) in enumerate(points):
if index==0:
ax.plot(x,y,"o",
color = "red",
markersize=size)
else:
ax.plot(x,y,"oy",
color="black",
markersize=size)
plt.show()