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))
复制代码

 

posted @   ascertain  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-11-30 MySQL测试数据库
点击右上角即可分享
微信分享提示