带有Python示例的math.sqrt()方法

Python math.sqrt() 方法

math.sqrt()方法数学模块的库方法,用于查找给定数字的平方根,它接受正数(整数或浮点数)并返回平方根。

注意:

  • 如果给定数字为负数,则返回“ ValueEroor”“ ValueError:math domain error”

  • 如果我们提供字符串以外的任何东西,除了数字,它还会返回“ ValueError”“ TypeError:需要浮点数”

它的语法 math.sqrt() 方法:

    math.sqrt(n)

Parameter(s): n-一个需要计算平方根的数字。

返回值: float-它返回一个浮点值,该浮点值是给定数字n的平方根。

示例

    Input:
    a = 2

    # 函数调用
    print(math.sqrt(a))

    Output:
    1.4142135623730951

Python代码演示示例 math.sqrt() 方法

# python代码演示示例 
# math.sqrt() method 

# 导入数学模块
import math 

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

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