简化根式时出现数学域错误

问题描述 投票:0回答:1

我正在尝试在Python 3.11.4中创建一个函数来简化根式表达式;第一步是找到该数字下方最接近的完全平方数。为此,我尝试创建一个函数,每次将数字减 1,检查根是否是整数,如果是则打印,如果不是则转到下一个最小数字。

import math


def closest_perfect_square(radical):
    while True:
        rad_root = math.sqrt(radical)
        if isinstance(rad_root, int):
            print(rad_root)
        else:
            radical -= 1


closest_perfect_square(60)

每次我使用任何部首运行此程序时,它都会给出

ValueError: math domain error
。如果有人能帮助我弄清楚为什么它一直给我这个错误,我将不胜感激。

python math square-root
1个回答
0
投票

利用上面的好的评论并添加更多需要的代码,以下是程序的重构版本。

import math

def closest_perfect_square(radical):
    while True and radical >= 0:        # As noted in the comments about negative numbers
        rad_root = math.sqrt(radical)
        if rad_root.is_integer():       # As noted in the comments about integer determination
            print(rad_root)
            break                       # Need this or otherwise the while loop will continue indefinitely 
        else:
            radical -= 1

closest_perfect_square(60)

另外需要注意的是需要“break”语句。否则,通过其他调整,程序将继续无限期地打印出最接近的根值。

测试此重构版本会产生以下终端输出。

craig@Vera:~/Python_Programs/Radical$ python3 Radical.py 
7.0

尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.