GID

Simple mathematical tricks in Python

· Georgios Is. Detorakis · 2 minutes read

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.

$ A = np.array([[1, 2], [2, 1]])
$ print(A)
[[1 2]
 [2 1]]

$ np.all(np.linalg.eigvals(A) > 0)
False       # A is not a positive definite matrix

$ A = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
print(A)
[[ 2 -1  0]
 [-1  2 -1]
 [ 0 -1  2]]

$ np.all(np.linalg.eigvals(A) > 0)
True        # A is positive definite

Random matrix with predetermined condition number

You can generate a random matrix with predetermined condition number by following method:

$ cond = 3.0
$ n, m = 3, 2
$ A = np.random.normal(0, 1, (m, n))
$ print(A)

[[ 0.24143692 -0.61944458]
 [ 0.49427012  1.34003024]
 [-1.08271826  0.91021725]]

$ k = min(m, n)
$ U, S, V = np.linalg.svd(A)

$ S = S[0] * (1.0 - ((cond - 1.0) / cond) * (S[0] - S) / (S[0] - S[-1]))

$ SMAT = np.zeros((m, n), dtype=complex) + 1e-9
$ smat[:k, :k] = np.diag(S)

$ B = U @ (SMAT @ V.T)

$ print("Desired condition number: ", cond)
Desired condition number: 3.0
$ print("Actual condition number", np.linalg.cond(B))
Actual 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 $.

# n >> k

$ 6 >> 1
3
$ 6 >> 2
0

Fast integer multiplication with two by left-bit-shift.

# n << k

$ 6 << 1
12
$ 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.

# n & 1

$ 6 & 1
0
$ 5 & 1
1

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 $.

# -n & n

$ -5 & 5
1
$ -6 & 6
2
$ -12 & 12
4