二元一次方程
昨天更新了个一元一次方程,算法太low
目前二元一次方程还存在的问题
不知道哪里有BUG,有时候求出来的解不对,只是无限接近正确答案
改进:
如果结果是小数的情况,以分数的形式显示
two_equation = input("请输入二元一次方程组,以空格隔开:")
two_equation_list = two_equation.split()
# 在数字和x,y之间加上乘号
two_equation_1_tmp = two_equation_list[0].replace("x", "*x")
two_equation_1 = two_equation_1_tmp.replace("y", "*y")
# print(two_equation_1)
two_equation_2_tmp = two_equation_list[1].replace("x", "*x")
two_equation_2 = two_equation_2_tmp.replace("y", "*y")
# print(two_equation_2)
"""二元一次方程有很多解法
其中可行的有代入法,
代入法太复杂,且感觉写起来比较困难,固想用后面的方法去求解:
ax+by=c
dx+ey=f
通过式子分别把a,b,c,d,e,f分离出来,然后直接代入求解"""
# 找出a,b,c
judge1 = int(two_equation_1.find("-"))
if judge1 == -1:
one_tmp_list = two_equation_1.split("+")
a_tmp = one_tmp_list[0].split("*")
a = int(a_tmp[0])
b_tmp = one_tmp_list[1].split("*")
b = int(b_tmp[0])
c_tmp = two_equation_1.split("=")
c = int(c_tmp[1])
# print(a, b, c)
else:
one_tmp_list = two_equation_1.split("-")
a_tmp = one_tmp_list[0].split("*")
a = int(a_tmp[0])
b_tmp = one_tmp_list[1].split("*")
b = int(b_tmp[0])
b = ~b + 1
c_tmp = two_equation_1.split("=")
c = int(c_tmp[1])
# print(a, b, c)
# 找出d,e,f
judge2 = int(two_equation_2.find("-"))
if judge2 == -1:
two_tmp_list = two_equation_2.split("+")
d_tmp = two_tmp_list[0].split("*")
d = int(d_tmp[0])
e_tmp = two_tmp_list[1].split("*")
e = int(e_tmp[0])
f_tmp = two_equation_2.split("=")
f = int(f_tmp[1])
# print(d, e, f)
else:
two_tmp_list = two_equation_2.split("-")
d_tmp = two_tmp_list[0].split("*")
d = int(d_tmp[0])
e_tmp = two_tmp_list[1].split("*")
e = int(e_tmp[0])
e = ~e + 1
f_tmp = two_equation_2.split("=")
f = int(f_tmp[1])
# print(d, e, f)
# 计算x,y
y = (f-c*d/a)/(e-b*d/a)
x = (f-c*e/b)/(d-a*e/b)
print("x=", x, sep='')
print("y=", y, sep='')