python里sqrt函数的作用与使用方法

  • Post category:Python

sqrt 函数是 Python 标准数学库 math 模块中的函数之一,用于计算数值的平方根。

使用方法

在使用 sqrt 函数之前,需要先导入 math 模块。导入方法:

import math

接下来,可以通过以下方式使用 sqrt 函数:

math.sqrt(x)

参数 x 为需要计算平方根的数字。返回值为 x 的平方根。

代码实例

以下两个代码实例演示了 sqrt 函数的使用方法。

实例1:求平方根

import math

x = 4
result = math.sqrt(x)
print("The square root of", x, "is", result)

运行结果:

The square root of 4 is 2.0

实例2:计算三角形斜边长度

import math

a = 3
b = 4
result = math.sqrt(a**2 + b**2)
print("The length of the hypotenuse is", result)

运行结果:

The length of the hypotenuse is 5.0

在这个例子中,代码计算了一个直角三角形的斜边长度。其中 ab 分别代表三角形的两个边,通过 Pythagorean 定理可以求出这个三角形斜边的长度。注意,由于 ** 是 Python 中用于指数计算的运算符,因此表达式 a**2 相当于 a 的平方。