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

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

在本文中,我们将展示如何在Python中不使用math模块进行平方根运算。以下是实现此任务的各种方法:

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

使用指数运算符**

在不使用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)。

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

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

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

示例

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

# 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模块计算给定数字平方根的方法。我们还学习了如何使用指数运算符(**)来计算平方或平方根。我们还使用了类似于二分查找的数学逻辑方法来计算平方。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程