當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python math.sqrt()用法及代碼示例


Python math.sqrt() 方法

math.sqrt() 方法是 math 模塊的一個庫方法,用於求給定數的平方根,它接受一個正數(整數或浮點數)並返回平方根。

注意:

  • 如果給定的數字是負數,則返回 "ValueEroor" - "ValueError:math domain error"。
  • 如果我們提供類似字符串的任何東西,除了數字,它還會返回 "ValueError" - “TypeError:a float is required”。

math.sqrt() 方法的語法:

    math.sqrt(n)

參數: n- 需要計算平方根的數字。

返回值: float- 它返回一個浮點值,它是給定數字的平方根n

例:

    Input:
    a = 2

    # function call
    print(math.sqrt(a))

    Output:
    1.4142135623730951

用於演示 math.sqrt() 方法示例的 Python 代碼

# python code to demonstrate example of 
# math.sqrt() method 

# importing math module
import math 

# numbers
a = 2
b = 12345
c = 10.21
d = 0
e = 0.0

# finding square roots of the numbers
print("square root of ", a, " is = ", math.sqrt(a))
print("square root of ", b, " is = ", math.sqrt(b))
print("square root of ", c, " is = ", math.sqrt(c))
print("square root of ", d, " is = ", math.sqrt(d))
print("square root of ", e, " is = ", math.sqrt(e))

輸出

square root of  2  is =  1.4142135623730951
square root of  12345  is =  111.1080555135405
square root of  10.21  is =  3.1953090617340916
square root of  0  is =  0.0
square root of  0.0  is =  0.0


相關用法


注:本文由純淨天空篩選整理自 math.sqrt() method with example in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。