NumPy教程:使用sqrt()函数计算数组元素的平方根

Python 的 NumPy 模块专门用于处理多维数组和矩阵运算。我们可以利用 NumPy 的 sqrt() 函数来计算矩阵中每个元素的平方根。

NumPy sqrt() 函数的常见用法

import numpy

array_2d = numpy.array([[1, 4], [9, 16]], dtype=numpy.float64)

print(array_2d)

array_2d_sqrt = numpy.sqrt(array_2d)

print(array_2d_sqrt)

输出结果:

[[ 1.  4.]
 [ 9. 16.]]
[[1. 2.]
 [3. 4.]]
Python NumPy Sqrt 示例

我们来看另一个例子,这次矩阵中的元素不是整数的平方。我们将直接在 Python 解释器中演示。

>>> import numpy
>>> 
>>> array = numpy.array([[1, 3], [5, 7]], dtype=numpy.float64)
>>> 
>>> print(array)
[[1. 3.]
 [5. 7.]]
>>> 
>>> array_sqrt = numpy.sqrt(array)
>>> 
>>> print(array_sqrt)
[[1.         1.73205081]
 [2.23606798 2.64575131]]
>>> 

NumPy sqrt() 函数处理无穷大的示例

接下来,我们探讨当矩阵元素为无穷大时,sqrt() 函数的行为。

>>> array = numpy.array([1, numpy.inf])
>>> 
>>> numpy.sqrt(array)
array([ 1., inf])
>>> 

处理复数

>>> array = numpy.array([1 + 2j, -3 + 4j], dtype=numpy.complex128)
>>> 
>>> numpy.sqrt(array)
array([1.27201965+0.78615138j, 1.        +2.j        ])
>>> 
NumPy Sqrt 复数示例

处理负数

>>> array = numpy.array([4, -4])
>>> 
>>> numpy.sqrt(array)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
array([ 2., nan])
>>> 

当对包含负数的矩阵元素执行平方根运算时,NumPy 会抛出运行时警告(RuntimeWarning: invalid value encountered in sqrt),并将对应元素的平方根结果返回为“nan”(非数字)。更多详细信息请参考 NumPy 官方文档。

bannerAds