如何在Python中不使用math模块的情况下进行平方根运算?


在本文中,我们将向您展示如何在不使用math模块的情况下在Python中执行平方根运算。以下是完成此任务的各种方法

  • 使用指数运算符 **
  • 使用数学逻辑

使用指数运算符 **

在不使用math模块的情况下,在Python中查找数字平方根最简单的方法是使用内置的指数运算符 **(它是指数运算符,因为它计算第一个操作数的第二个操作数次方)。

算法(步骤)

以下是执行所需任务的算法/步骤:

  • 创建一个变量来存储输入数字。

  • 使用指数运算符 (**) 获取数字的平方根。

  • 打印输入数字的平方根。

示例

以下程序返回输入数字的平方根,不使用math模块,并使用** 运算符

# input number inputNumber = 25 # getting the square root of a number using the exponential operator** squareRoot = inputNumber**(1/2) # printing the square root of a number print("The square root of", inputNumber, "=", squareRoot)

输出

执行上述程序将生成以下输出:

('The square root of', 25, '=', 1)

在这个方法中,我们取一个数字,并使用 ** 运算符计算其平方根,将指数值传递为 (1/2) 或 0.5,然后打印结果。

使用数学逻辑

此方法类似于二分查找。

算法(步骤)

以下是执行所需任务的算法/步骤:

  • 创建一个变量来存储输入数字。

  • 将最小值初始化为 0。

  • 将最大值初始化为输入数字。

  • 使用for循环重复循环 10 次。

  • 通过将最小值和最大值相加除以 2(获取最小值和最大值的平均值)来获取最小值和最大值的中间值。

  • 使用** 运算符计算中间值的平方,并将其存储在一个变量中。

  • 使用if条件语句检查中间值的平方值是否等于输入数字,如果为真,则使用break语句中断代码(Python中的break语句终止当前循环,并在下一条语句处恢复执行,就像C语言中的传统break一样)。

  • 否则,检查中间值的平方值是否大于输入数字,如果为真,则将最大值设置为中间值。

  • 否则,如果中间值的平方值小于数字,则将最小值设置为中间值。

  • 打印中间值,即输入数字的结果平方根。

示例

以下程序返回输入数字的平方根,不使用math模块,并使用数学逻辑:

# input number number = 9 # initializing minimum value as 0 minimum = 0 # initializing maximum value with input number maximum =number # repeating the loop 10 times using for loop for i in range(10): # getting the middle value middle =(minimum+maximum)/2 # getting the square of the middle value squareValue=middle**2 # checking whether the square value of the middle value is equal to the number if squareValue ==number: # break the code if the condition is true break # checking whether the square value of the middle value is more than the number # taking max value as the middle value if the condition is true maximum=middle # else if the square value of the middle value is less than the number # taking the min value as a middle minimum=middle # printing the middle value which is the resultant square root print("The resultant square root of", number, "=", middle)

输出

执行上述程序将生成以下输出:

('The resultant square root of', 9, '=', 4)

结论

在本文中,我们学习了两种不同的方法来计算给定数字的平方根,而无需使用math模块。我们还学习了如何使用指数运算符(**)计算平方或平方根。我们还使用类似于二分查找的数学逻辑方法计算了平方。

更新于:2023年8月28日

32K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.