# Help with numerically unstable algorithm

**URL:** <https://discourse.julialang.org/t/help-with-numerically-unstable-algorithm/104911>\
**Category:** Numerics\
**Tags:** question, algorithm\
**Created:** [October 12, 2023, 8:19pm UTC](https://discourse.julialang.org/t/help-with-numerically-unstable-algorithm/104911 "2023-10-12T20:19:27Z")\
**Posts on this page:** 1\
**Showing post:** 6

<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 18, 2023, 2:22pm UTC](https://discourse.julialang.org/t/help-with-numerically-unstable-algorithm/104911/6 "2023-10-18T14:22:29Z")

</div>

> [@enweg](#):
>
> If you have another way to draw a random companion matrix with real eigenvalues

What sort of “companion matrix” do you want? That term usually implies a matrix whose eigenvalues match the roots of a given polynomial, but in this case you aren’t supplying a polynomial so I’m not sure what you mean.

If you just want an n \times n matrix A with given n eigenvalues `λ` (e.g. `λ = randn(n)`), why not simply do `X = randn(n, n)` followed by `A = X * Diagonal(λ) / X`? (Or, if you want a Hermitian A, you could get a [random orthogonal matrix](https://arxiv.org/abs/math-ph/0609050) Q by doing `QR = qr(X); Q = QR.Q * Diagonal(sign.(diag(QR.R)))` and then do `A = Hermitian(Q * Diagonal(λ) * Q')`.)

(If you then want a polynomial with those roots, given the matrix, you can [compute the characteristic polynomial](https://discourse.julialang.org/t/code-to-calculate-characteristic-polynomial/19903). Numerically, working with this polynomial directly is not usually a good idea, however.)

---

_[View the full topic](https://discourse.julialang.org/t/help-with-numerically-unstable-algorithm/104911)._
