求两条直线的交点和抛物线的极值点 Python

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()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值