python的艰难学习之路-求二元一次方程的解

二元一次方程

昨天更新了个一元一次方程,算法太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='')


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值