Python中的numpy.hypot()
这个数学函数帮助用户计算直角三角形的斜边,给定其边和垂线。计算结果等同于sqrt(x12 + x22),按元素计算。
语法 :
numpy.exp2(arr1, arr2[, out]) = ufunc 'hypot') :
参数 :
arr1, arr2 : [array_like] 三角形的腿(边和垂直线)。
out : [ndarray, optional] 输出结果的数组。
返回 :
具有直角三角形斜边的阵列。
代码#1 :
# Python3 program explaining
# hypot() function
import numpy as np
leg1 = [12, 3, 4, 6]
print ("leg1 array : ", leg1)
leg2 = [5, 4, 3, 8]
print ("leg2 array : ", leg2)
result = np.hypot(leg1, leg2)
print("\nHypotenuse is as follows :")
print(result)
输出 :
leg1 array : [12, 3, 4, 6]
leg2 array : [5, 4, 3, 8]
Hypotenuse is as follows :
[ 13. 5. 5. 10.]
代码#2:使用二维数组工作
# Python3 program explaining
# hypot() function
import numpy as np
leg1 = np.random.rand(3, 4)
print ("leg1 array : \n", leg1)
leg2 = np.ones((3, 4))
print ("leg2 array : \n", leg2)
result = np.hypot(leg1, leg2)
print("\nHypotenuse is as follows :")
print(result)
输出 :
leg1 array :
[[ 0.57520509 0.12043366 0.50011671 0.13800957]
[ 0.0528084 0.17827692 0.44236813 0.87758732]
[ 0.94926413 0.47816742 0.46111934 0.63728903]]
leg2 array :
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
Hypotenuse is as follows :
[[ 1.15362944 1.00722603 1.11808619 1.0094784 ]
[ 1.00139339 1.01576703 1.09347591 1.33047342]
[ 1.37880469 1.10844219 1.10119528 1.18580661]]
代码3:等同于sqrt(x1)2 + x22),从元素上看。
# Python3 program explaining
# hypot() function
import numpy as np
leg1 = np.random.rand(3, 4)
print ("leg1 array : \n", leg1)
leg2 = np.ones((3, 4))
print ("leg2 array : \n", leg2)
result = np.sqrt((leg1 * leg1) + (leg2 * leg2))
print("\nHypotenuse is as follows :")
print(result)
输出 :
leg1 array :
[[ 0.7015073 0.89047987 0.1595603 0.27557254]
[ 0.67249153 0.16430312 0.70137114 0.48763522]
[ 0.68067777 0.52154819 0.04339669 0.2239366 ]]
leg2 array :
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
Hypotenuse is as follows :
[[ 1.15362944 1.00722603 1.11808619 1.0094784 ]
[ 1.00139339 1.01576703 1.09347591 1.33047342]
[ 1.37880469 1.10844219 1.10119528 1.18580661]]