Python: Guess and Check algorithms, Approximate solutions, Bisection method
判断一个整数是否为完全立方数 cubic number:
import math cubical = int(input('number: ')) def is_cubical(cubical: int): n = math.ceil(pow(cubical.__abs__(), 1 / 3)) # for v in range(abs(cubical) + 1): for v in range(n + 1): if pow(v, 3) == abs(cubical): if cubical < 0: return True, -v else: return True, v return False, None print(is_cubical(cubical))
Approximation: 近似算法
import math cubical = float(input('number: ')) def cube_root(cubical: float): guess = 0.0 increment = 0.0001 epsilon = 0.001 # the precision must below epsilon, need to less than increment count = 0 while abs(pow(guess, 3) - abs(cubical)) >= epsilon and guess <= abs(cubical): guess += increment count += 1 if abs(pow(guess, 3) - abs(cubical)) >= epsilon: return None, count else: if cubical < 0: return -guess, count else: return guess, count print(cube_root(cubical))
Bisection 二分法:
cubical = float(input('number: ')) def cube_root(cubical: float): epsilon = 0.001 low = 0.0 high = abs(cubical) middle = (low + high) / 2 while abs(pow(middle, 3) - abs(cubical)) >= epsilon: if pow(middle, 3) > abs(cubical): high = middle else: low = middle middle = (low + high) / 2 return middle print(cube_root(cubical))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2020-11-30 MySQL测试数据库