1. 求两条直线的交点,联立方程即可,公式如下:
计算两条直线交点代码:
#计算两条直线的交点
#y = a1*x + b1
#y = a2*x + b2
#如果没有交点 抛出异常并返回None
def cal_intersection(a1,b1,a2,b2):
try:
x = (b2-b1)/(a1-a2)
y = a1*(b2-b1)/(a1-a2) + b1
return (x,y)
except Exception as e:
print(str(e))
return None
2. 求抛物线的极值点,计算导数等于0时x的值,再带入公式求出y,公式如下:
计算抛物线极值点代码:
# 抛物线:y = a*x**2 + b*x + c
# 若a为0 抛出异常并返回None
def getExtremePoint(a,b,c):
try:
x = -(b/2/a)
y = (4*a*c - b**2)/4/a
return (x,y)
except Exception as e:
print(str(e))
return None
验证求直线交点代码:
import numpy as np
import matplotlib.pyplot as plt
a1,b1,a2,b2 = np.random.rand(4)
input_x = np.arange(-5,5,0.1)
y_predict2 = a1 * input_x + b1
y_predict1 = a2 * input_x + b2
#求交点
intersection = cal_intersection(a1,b1,a2,b2)
#画图
plt.plot(input_x,y_predict1,color='r',linestyle='-',marker='.',label=u"predict")
plt.plot(input_x,y_predict2,color='g',linestyle='-',marker='.',label=u"predict")
plt.scatter(intersection[0],intersection[1],color='b',linestyle='-',marker='.',label=u"intersection",linewidth=11)
plt.legend(loc='upper left')
plt.show()
验证求抛物线极值点代码:
import numpy as np
import matplotlib.pyplot as plt
a,b,c = (-1) ** np.random.randint(0,2)*np.random.rand(3)
input_x = np.arange(-5,5,0.1)
y_predict = a * input_x **2 + b * input_x + c
#求极值点
extreme = getExtremePoint(a,b,c)
#画图
plt.plot(input_x,y_predict,color='r',linestyle='-',marker='.',label=u"predict")
plt.scatter(extreme[0],extreme[1],color='b',linestyle='-',marker='.',label=u"extreme",linewidth=11)
plt.legend(loc='upper left')
plt.show()