Wav3Motion 发表于 2022-9-19 00:59:51

应付python软件实验作业之二分查找求解立方根

#二分法求立方根(全部实数)
Cube = float(input("请输入一个数字:"))
Ep = 1E-6
Cube_1 = abs(Cube)
lower = 1
higher = Cube_1
Guess = (lower+higher)/2.0
if Cube == 0:
    print("0是",Cube,"立方根的解")
elif Cube_1 > 1:
    while abs(Guess**3 - Cube_1) >= Ep:
      if Guess**3 < Cube_1:
            lower = Guess
      else:
            higher = Guess
      Guess = (higher+lower)/2.0
    if Cube > 0:
      print(Guess,"是",Cube,"立方根的近似解")
    if Cube < 0:
      print("-",Guess,"是",Cube,"立方根的近似解")
elif Cube_1 > 0 and Cube_1 < 1:
    lower = Cube_1
    higher = 1.0
    Guess = (lower+higher)/2.0
    while abs(Guess ** 3 - Cube_1) >= Ep:
      if Guess**3 < Cube_1:
            lower = Guess
      else:
            higher = Guess
      Guess = (higher+lower)/2.0
    if Cube > 0:
      print(Guess,"是",Cube,"立方根的近似解")
    if Cube < 0:
      print("-",Guess,"是",Cube,"立方根的近似解")


可以说是能运行但是十分繁杂甚至九分 有啥改进措施还望提提
页: [1]
查看完整版本: 应付python软件实验作业之二分查找求解立方根