Python 的 sqrt():math 函数

2024 年 8 月 29 日 | 阅读 3 分钟

sqrt() 函数是 Python 中用于执行数学运算的内置函数。sqrt() 函数用于返回导入数字的平方根。

在本教程中,我们将讨论如何在 Python 中使用 sqrt() 函数。

语法

参数

'N' 是任何大于或等于 0 的数字 (N >= 0)。

返回值

它将返回作为参数传递的数字 "N" 的平方根。

示例

输出

The square root of 7:  2.6457513110645907
The square root of 49:  7.0
The square root of 115:  10.723805294763608

Error

如果作为参数传递的数字小于 "0",我们会在执行 sqrt() 函数时遇到一个运行时错误。

示例

输出

The square root of 16:  4.0
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-79d85b7d1d62> in <module>
      5 
      6 # printing the error when x less than 0
----> 7 print ("The square root of -16: ", m.sqrt(-16))
      8 

ValueError: math domain error

说明

例如,当我们首先传递 "16" 作为参数时,输出为 "4",但对于小于 "0" 的 "-16",我们收到一个错误,提示 "math domain error"。

应用

我们还可以使用 sqrt() 函数来创建一个用于执行数学运算的应用程序。假设我们有一个数字 "N",我们需要检查它是否是质数。

方法

我们将采用以下方法:

  • 步骤 1: 我们将导入 math 模块。
  • 步骤 2: 我们将创建一个名为 "check_if" 的函数,用于检查给定数字是否为质数。
  • 步骤 3: 我们将检查数字是否等于 1。如果 "是",它将返回 false。
  • 步骤 4: 我们将运行一个从范围 "2" 到 "sqrt(N)" 的 for 循环。
  • 步骤 5: 我们将检查给定范围内的任何数字是否能整除 "N"。

示例

输出

#1:

Enter the number you want to check:  12
The number is not prime

#2:

Enter the number you want to check:  11
The number is prime

#3:

Enter the number you want to check:  53
The number is prime

结论

在本教程中,我们讨论了如何使用 Python 的 sqrt() 函数来计算大于 0 的任何数字的平方根。