numpy 100题练习 Day5

https://github.com/rougier/numpy-100

How to sum a small array faster than np.sum?

1
2
3
4
# Author: Evgeni Burovski

Z = np.arange(10)
np.add.reduce(Z)

Consider two random array A and B, check if they are equal

1
2
3
4
5
6
7
8
9
10
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)

# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)

# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)

Make an array immutable (read-only)

1
2
3
Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1

Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates

1
2
3
4
5
6
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)

Create random vector of size 10 and replace the maximum value by 0

1
2
3
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)

Create a structured array with x and y coordinates covering the [0,1]x[0,1] area

1
2
3
4
Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
np.linspace(0,1,5))
print(Z)

Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))

1
2
3
4
5
6
# Author: Evgeni Burovski

X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
1
2
3
4
5
6
7
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)

How to print all the values of an array?

1
2
3
np.set_printoptions(threshold=np.nan)
Z = np.zeros((16,16))
print(Z)

How to find the closest value (to a given scalar) in a vector?

1
2
3
4
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])