# Singular exception when it shouldn't happen, tol for inv?

**URL:** <https://discourse.julialang.org/t/singular-exception-when-it-shouldnt-happen-tol-for-inv/16043>\
**Category:** Optimization (Mathematical)\
**Tags:** linearalgebra\
**Created:** [October 8, 2018, 8:31pm UTC](https://discourse.julialang.org/t/singular-exception-when-it-shouldnt-happen-tol-for-inv/16043 "2018-10-08T20:31:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Zhiye\_Xia](https://avatars.discourse-cdn.com/v4/letter/z/bcef8e/32.png) [@Zhiye\_Xia](https://discourse.julialang.org/u/Zhiye_Xia)\
**Post date:** [October 8, 2018, 8:31pm UTC](https://discourse.julialang.org/t/singular-exception-when-it-shouldnt-happen-tol-for-inv/16043/1 "2018-10-08T20:31:58Z")

</div>

```julia
x = somevector
X = hcat(ones(length(x)), x, x.^2)
inv(X'* X)

Result: SingularException(3)

```

somevector may be a random vector with multiple zeros but more than 2 non-zero & non-equal elements are ensured to make X to be full rank.

When I replicate this in R, it would give a similar error message, which can be resolved by tweaking the tolerance for inverse function to a smaller number. However, I am not sure if that’s where the problem is, and if it is, what’s the corresponding solution in Julia?

Any help would be much appreciated. Thanks.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [October 8, 2018, 9:15pm UTC](https://discourse.julialang.org/t/singular-exception-when-it-shouldnt-happen-tol-for-inv/16043/2 "2018-10-08T21:15:48Z")

</div>

If you have a nearly rank-deficient `X`, then you should try to avoid `X' * X` entirely if possible because it squares the condition number — any calculation that you do with `X' * X`, with any language/algorithm, is going to be much more sensitive to small errors than working directly with `X`.

If you are solving a least-square problem, for example, you can just use `X \ b` to get the fit coefficients.

More generally, you might want to work with the SVD or QR factorization of `X`.
