Simple mathematical tricks in Python
In this post, you can find some helpful mathematical tips and tricks in the Python programming language.
Positive definite matrix
Check if a given matrix $ \bf{A} $ is positive definite. If all the eigenvalues of matrix $ \bf{A} $ are positive then the matrix is positive definite.
1$ A = np.array([[1, 2], [2, 1]])
2$ print(A)
3[[1 2]
4 [2 1]]
5
6$ np.all(np.linalg.eigvals(A) > 0)
7False # A is not a positive definite matrix
8
9$ A = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
10print(A)
11[[ 2 -1 0]
12 [-1 2 -1]
13 [ 0 -1 2]]
14
15$ np.all(np.linalg.eigvals(A) > 0)
16True # A is positive definite
Random matrix with predetermined condition number
You can generate a random matrix with predetermined condition number by following method:
1$ cond = 3.0
2$ n, m = 3, 2
3$ A = np.random.normal(0, 1, (m, n))
4$ print(A)
5
6[[ 0.24143692 -0.61944458]
7 [ 0.49427012 1.34003024]
8 [-1.08271826 0.91021725]]
9
10$ k = min(m, n)
11$ U, S, V = np.linalg.svd(A)
12
13$ S = S[0] * (1.0 - ((cond - 1.0) / cond) * (S[0] - S) / (S[0] - S[-1]))
14
15$ SMAT = np.zeros((m, n), dtype=complex) + 1e-9
16$ smat[:k, :k] = np.diag(S)
17
18$ B = U @ (SMAT @ V.T)
19
20$ print("Desired condition number: ", cond)
21Desired condition number: 3.0
22$ print("Actual condition number", np.linalg.cond(B))
23Actual condition number: 2.9999999999999973
Integer operations
Fast integer division by two (rounded down). In this case, we have to perform a bit shift to the right by $ k $. $ k $ indicates the power of two $ 2^k $.
1# n >> k
2
3$ 6 >> 1
43
5$ 6 >> 2
60
Fast integer multiplication with two by left-bit-shift.
1# n << k
2
3$ 6 << 1
412
5$ 6 << 24
Check if an integer $ n $ is even or odd by performing a binary and operation. If the result of the following operation is 0, then n is even, otherwise is an odd number.
1# n & 1
2
3$ 6 & 1
40
5$ 5 & 1
61
You can find the maximum power-of-two that divides an integer $ n $ by performing an and operation between the integers $ n $ and its additive inverse $ -n $.
1# -n & n
2
3$ -5 & 5
41
5$ -6 & 6
62
7$ -12 & 12
84