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 的數字的平方根。
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/130600.html