求两条直线方程的交点
帮一位英国留学的小伙伴写的作业
题目要求:
python3代码实现:
"""
y1 = a * x1 + b * x1 + c = (a+b) * x1 + c
y2 = d * x2 + e * x2 + f = (d+e) * x2 + f
## 条件约束:
1. 用户输入a,b,c,d,e,f来得到两个方程的交点
2. 对于用户的输入进行错误异常处理
3. 画坐标系以及两条直线方程
4. 找到交点,确保程序能够对不同的情形进行处理,例如没有交点,即两条直线平行的情况
5. 找到的交点,能够在图上突出的展示出来最好了
6. 关注用户交互方面
7. 归档,并及时交作业
8. 更多挑战,可以尝试考虑求二次方程的交点
"""
import numpy as np
import matplotlib.pyplot as plt
a = int(input('input a: '))
b = int(input('input b: '))
c = int(input('input c: '))
d = int(input('input d: '))
e = int(input('input e: '))
f = int(input('input f: '))
# 创建x坐标
x = np.arange(-10, 10, 1)
def draw_graph():
plt.title('mini_project')
plt.plot(x, y1(x, k1, c), label='y1')
plt.plot(x, y2(x, k2, f), label='y2')
# plt.plot(x_intersection, y_intersection, 'ro', label='intersection')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend()
plt.show()
def y1(x_y1, k1, c_y1):
y = [k1 * i + c_y1 for i in x_y1]
return y
def y2(x_y2, k2, c_y2):
y = [k2 * i + c_y2 for i in x_y2]
return y
k1 = a + b
k2 = d + e
x_intersection = 0
y_intersection = 0
# 两条直线重合
if k1 == 0 and k2 == 0 and c == f:
print('两条直线重合')
draw_graph()
# 两条直线平行
if k1 == k2:
print('两条直线平行,无交点!')
# 有交点:
if k1 != k2:
x_intersection = (f - c) / (k1 - k2)
y_intersection = k1 * x_intersection + c
plt.plot(x_intersection, y_intersection, 'ro', label='intersection')
draw_graph()