如何在不使用 Python 中的数学模块的情况下执行平方根?

pythonserver side programmingprogramming更新于 2023/12/17 8:49:00

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

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

使用指数运算符**

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

算法(步骤)

以下是执行所需任务要遵循的算法/步骤-

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

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

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

示例

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

# 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)

结论

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


相关文章