Skip to content

Instantly share code, notes, and snippets.

@bstellato
Last active October 11, 2022 20:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bstellato/23322fe5d87bb71da922fbc41d658079 to your computer and use it in GitHub Desktop.
Save bstellato/23322fe5d87bb71da922fbc41d658079 to your computer and use it in GitHub Desktop.
Generate matrix with predefined condition number
# Construct random matrix P with specified condition number
#
# Bierlaire, M., Toint, P., and Tuyttens, D. (1991).
# On iterative algorithms for linear ls problems with bound constraints.
# Linear Algebra and Its Applications, 143, 111–143.
#
cond_P = 10**2 # Condition number
log_cond_P = np.log(cond_P)
exp_vec = np.arange(-log_cond_P/4., log_cond_P * (n + 1)/(4 * (n - 1)), log_cond_P/(2.*(n-1)))
s = np.exp(exp_vec)
S = np.diag(s)
U, _ = la.qr((np.random.rand(n, n) - 5.) * 200)
V, _ = la.qr((np.random.rand(n, n) - 5.) * 200)
P = U.dot(S).dot(V.T)
P = P.dot(P.T)
@mdbenito
Copy link

This will fail for some combinations of matrix size and condition number, e.g. n = 4, cond_P = 23. Truncate exp_vec to size n to fix it with

exp_vec = exp_vec[:n]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment