首页 > 编程知识 正文

Python 的数学函数sqrt()

时间:2023-11-26 13:13:13 阅读:309381 作者:MRPK

sqrt()函数是 Python 中的内置函数,用于执行与数学相关的操作。 sqrt()函数用于返回任何导入数字的平方根。

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

语法:


math.sqrt(N)

参数:

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

返回:

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

示例:


# importing the math module 
import math as m

# printing the square root of 7 
print ("The square root of 7: ", m.sqrt(7)) 

# printing the square root of 49
print ("The square root of 49: ", m.sqrt(49)) 

# printing the square root of 115
print ("The square root of 115: ", m.sqrt(115))

输出:

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

错误

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

示例:


# import the math module 
import math as m

print ("The square root of 16: ", m.sqrt(16)) 

# printing the error when x less than 0 
print ("The square root of -16: ", m.sqrt(-16))

输出:

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”,我们得到了一个错误,说是“数学域错误”。

应用

我们也可以使用 sqrt()函数来创建一个执行数学函数的应用。假设我们有一个数字“N”,我们必须检查它是否是质数。

方法:

我们将使用以下方法:

  • 步骤 1: 我们将导入math模块。
  • 第二步:我们将创建一个函数“check_if”,用于检查给定的数字是否是质数。
  • 第三步:我们会检查数字是否等于 1。如果“是”,它将返回 false。
  • 步骤 4: 我们将运行一个从范围“2”到“sqrt(N)”的 for循环。
  • 步骤 5: 我们将检查给定范围之间是否有任何数字除以“N”。

示例:


import math as M

# Creating a function for checking if the number is prime or not 
def check_if(N):
    if N == 1:
        return False

        # Checking from 1 to sqrt(N) 
    for K in range(2, (int)(M.sqrt(N)) + 1):
        if N % K == 0:
            return False 
    return True

# driver code
N = int( input("Enter the number you want to check: "))
if check_if(N):
    print ("The number is prime") 
else:
    print ("The number is not prime")

输出:

#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 的数字的平方根。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。