这是个人整理的一些用python进行数值计算的常用操作。
>>> 1/2
0.5
>>> 2.5/5.0
0.5
>>> 5/7.5
0.6666666666666666
9//30
Out[1]: 0
9%30
Out[2]: 9
import math
math.sqrt(36)
Out[3]: 6.0
import math
math.pow(6, 2)
Out[4]: 36.0
也可以
>>>a = 2**(-3)
>>>print(a)
0.125
abs()是python3 内置函数
a = -2
b = -3
c = abs(a + b)
print(c)
Out[5]: 5
>>> import math
>>> math.log(2,16)
0.25
>>> math.log(16,2)
4.0
>>> math.log2(16)
4.0
>>> math.log16(2)
Traceback (most recent call last):
File "" , line 1, in <module>
AttributeError: module 'math' has no attribute 'log16'
>>>
注:并不是所有的对数都可以写成math.logN(M)
的形式,math里面只有log10、log2、log1p、log
。log1p是底为e的log函数,同log,计算显示表达式为 f ( x ) = l n ( 1 + x ) f(x)=ln(1+x) f(x)=ln(1+x)。因此math.log(10,math.e)
的结果和math.log(11,math.e)
的结果相同。
>>> math.log(10,math.e)
2.302585092994046
>>> math.log1p(10)
2.3978952727983707
>>> math.log(11,math.e)
2.3978952727983707
x = np.array([[0, 2], [1, 1], [2, 0]]).T
print(x)
输出
[[0 1 2]
[2 1 0]]
cov = np.cov(x)
print(cov)
输出
[[ 1. -1.]
[-1. 1.]]
注意:如果每行不是代表一个变量,那么了有两种方法。第一种就像上面那样先将矩阵或者数组转置,再求协方差;第二种是用cov函数中的rowvar参数来控制,rowvar默认为True,如果每列代表一个变量的话,可以将其设为False。
# transfer the latitude and longitude to distance
def geo_distance(lng1,lat1,lng2,lat2):
lng1, lat1, lng2, lat2 = map(radians, [lng1, lat1, lng2, lat2])
dist_lon = lng2-lng1
dist_lat = lat2-lat1
a = sin(dist_lat/2)**2 + cos(lat1) * cos(lat2) * sin(dist_lon/2)**2
dis = 2*asin(sqrt(a))*6371*1000
return dis
long_dist = geo_distance(122.0, 38.0, 122.6, 38.0)
lati_dist = geo_distance(122.0, 37.2, 122.0, 38.0)
print(long_dist, lati_dist)
# 结果为
52573.587711031105 88955.94131564711
参考我的另一篇博文:Python 计算任意两向量之间的夹角。