sqrt()
函数计算数组中每个元素的平方根。
示例
import numpy as np
array1 = np.array([4, 9, 16, 25])
# compute square root of each element in array1
result = np.sqrt(array1)
print(result)
# Output: [2. 3. 4. 5.]
sqrt() 语法
sqrt()
的语法是
numpy.sqrt(array, out=None, where=True)
sqrt() 参数
sqrt()
函数接受以下参数
array
- 计算平方根的输入数组out
(可选) - 用于存储结果的输出数组where
(可选) - 指定应更新哪些元素的条件
sqrt() 返回值
sqrt()
函数返回一个数组,其中包含输入数组中每个元素的平方根。
示例 1:查找数组元素的平方根
import numpy as np
array1 = np.array([36, 49, 100, 256])
# compute square root of each element in array1
result = np.sqrt(array1)
print(result)
输出
[ 6. 7. 10. 16.]
在上面的示例中,我们使用 sqrt()
函数来计算 array1 中每个元素的平方根。
在我们的例子中,36 的平方根是 6,49 的平方根是 7,100 的平方根是 10,256 的平方根是 16。因此,结果数组是 [ 6. 7. 10. 16.]
。
注意:即使结果值是浮点数,它们也是输入数组中相应整数的确切平方根
示例 2:使用 out 将结果存储在所需的数组中
import numpy as np
# create a 2-D array
array1 = np.array([[4, 9, 16],
[25, 36, 49]])
# create an empty array with the same shape as array1
result = np.zeros_like(array1, dtype=float)
# calculate the square root of each element in array1 and store the result in result
np.sqrt(array1, out=result)
print(result)
输出
[[2. 3. 4.] [5. 6. 7.]]
在此,sqrt()
与 out
参数一起设置为 result。这确保计算平方根的结果存储在 result 中。
示例 3:使用 where 计算过滤后数组的平方根
import numpy as np
array1 = np.array([4, 9, 16, 25])
# compute the square root of each element in array1
# where the element is odd (arr%2==1)
result = np.sqrt(array1, where=(array1 % 2 == 1))
print(result)
输出
[0. 3. 0. 5.]