I am trying to generate and solve a matrix that tends towards being singular using variable arbitrary precision to ensure accuracy. Consider, for example, a matrix with tunable singularity:

matrix[n_, prec_] := {{1, 0}, {0, N[1/n, prec]}}

We can use a while loop with Check to determine the appropriate level of precision needed to avoid a badly conditioned matrix:

prec = 1;
 Check[LinearSolve@matrix[10^6, prec], err] === err,
 prec = prec + 1;
sol = LinearSolve@matrix[10^4, prec]

Running this snippet indicates that prec must be 8 to avoid a badly conditioned matrix.

This isn't a big deal for this matrix function, because it's computationally trivial to generate and solve. However, for larger, more expensive to compute matrix functions, it would be nice to not waste the results of the evaluation of matrix and the LinearSolve used in the Check.

Is there a way to avoid that wasted computation? Additionally, is there a better way to do this automatic precision tuning (other than adjusting the step size for the increase in prec)?

  • $\begingroup$ Would Check[sol = LinearSolve@matrix[10^6, prec], err] === err do what you want? $\endgroup$
    – MarcoB
    Jan 22, 2021 at 18:53
  • $\begingroup$ @MarcoB Doh! Of course. How did I miss that. $\endgroup$
    – Eli Lansey
    Jan 22, 2021 at 18:56
  • $\begingroup$ For the second question, you may be interested in How can I tell if a matrix is ill-conditioned or singular. $\endgroup$
    – MarcoB
    Jan 22, 2021 at 19:28
  • 1
    $\begingroup$ @MarcoB I also want the results from LinearSolve, so just running LinearSolve and monitoring for the warning is sufficient. But, it's a good idea to use the "ConditionNumber" argument to estimate the precision needed. Going to think on that. $\endgroup$
    – Eli Lansey
    Jan 22, 2021 at 20:09


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.