Tests: Draw well-conditioned diagonals for the QR determinant checks

libeigen/eigen!2980

Closes #3134

Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/test/qr.cpp b/test/qr.cpp
index 18d5253d..a5962de 100644
--- a/test/qr.cpp
+++ b/test/qr.cpp
@@ -52,8 +52,6 @@
 void qr_invertible() {
   using std::abs;
   using std::log;
-  using std::max;
-  using std::pow;
   typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
   typedef typename MatrixType::Scalar Scalar;
 
@@ -76,7 +74,7 @@
 
   // now construct a matrix with prescribed determinant
   m1.setZero();
-  for (int i = 0; i < size; i++) m1(i, i) = internal::random<Scalar>();
+  setRandomWellConditionedDiagonal(m1);
   Scalar det = m1.diagonal().prod();
   RealScalar absdet = abs(det);
   m3 = qr.householderQ();  // get a unitary
@@ -84,12 +82,8 @@
   qr.compute(m1);
   VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());
   VERIFY_IS_APPROX(numext::sign(det), qr.signDeterminant());
-  // This test is tricky if the determinant becomes too small.
-  // Since we generate random numbers with magnitude range [0,1], the average determinant is 0.5^size
-  RealScalar tol =
-      numext::maxi(RealScalar(pow(0.5, size)), numext::maxi<RealScalar>(abs(absdet), abs(qr.absDeterminant())));
-  VERIFY_IS_MUCH_SMALLER_THAN(abs(det - qr.determinant()), tol);
-  VERIFY_IS_MUCH_SMALLER_THAN(abs(absdet - qr.absDeterminant()), tol);
+  VERIFY_IS_APPROX(det, qr.determinant());
+  VERIFY_IS_APPROX(absdet, qr.absDeterminant());
 }
 
 template <typename MatrixType>
diff --git a/test/qr_colpivoting.cpp b/test/qr_colpivoting.cpp
index b4f5188..7eb4be0 100644
--- a/test/qr_colpivoting.cpp
+++ b/test/qr_colpivoting.cpp
@@ -62,9 +62,7 @@
   // now construct a (square) matrix with prescribed determinant
   Index size = internal::random<Index>(2, 20);
   matrix.setZero(size, size);
-  for (int i = 0; i < size; i++) {
-    matrix(i, i) = internal::random<Scalar>();
-  }
+  setRandomWellConditionedDiagonal(matrix);
   Scalar det = matrix.diagonal().prod();
   RealScalar absdet = numext::abs(det);
   CompleteOrthogonalDecomposition<MatrixType> cod2(matrix);
@@ -275,7 +273,7 @@
 
   // now construct a matrix with prescribed determinant
   m1.setZero();
-  for (int i = 0; i < size; i++) m1(i, i) = internal::random<Scalar>();
+  setRandomWellConditionedDiagonal(m1);
   Scalar det = m1.diagonal().prod();
   RealScalar absdet = abs(det);
   m3 = qr.householderQ();  // get a unitary
diff --git a/test/qr_fullpivoting.cpp b/test/qr_fullpivoting.cpp
index f2595da..b24dd12 100644
--- a/test/qr_fullpivoting.cpp
+++ b/test/qr_fullpivoting.cpp
@@ -97,7 +97,7 @@
 
   // now construct a matrix with prescribed determinant
   m1.setZero();
-  for (int i = 0; i < size; i++) m1(i, i) = internal::random<Scalar>();
+  setRandomWellConditionedDiagonal(m1);
   Scalar det = m1.diagonal().prod();
   RealScalar absdet = abs(det);
   m3 = qr.matrixQ();  // get a unitary
diff --git a/test/qr_rand_colpivoting.cpp b/test/qr_rand_colpivoting.cpp
index 35cccc7..aa95a82 100644
--- a/test/qr_rand_colpivoting.cpp
+++ b/test/qr_rand_colpivoting.cpp
@@ -162,7 +162,7 @@
 
   // Now construct a matrix with prescribed determinant and verify det/sign.
   m1.setZero();
-  for (int i = 0; i < size; i++) m1(i, i) = internal::random<Scalar>();
+  setRandomWellConditionedDiagonal(m1);
   Scalar det = m1.diagonal().prod();
   RealScalar absdet = abs(det);
   m3 = qr.householderQ();
@@ -262,9 +262,7 @@
 
   Index size = internal::random<Index>(2, 20);
   matrix.setZero(size, size);
-  for (int i = 0; i < size; i++) {
-    matrix(i, i) = internal::random<Scalar>();
-  }
+  setRandomWellConditionedDiagonal(matrix);
   Scalar det = matrix.diagonal().prod();
   RealScalar absdet = numext::abs(det);
   RandCompleteOrthogonalDecomposition<MatrixType> cod2;
diff --git a/test/random_matrix_helper.h b/test/random_matrix_helper.h
index 6f3e677..b96a371 100644
--- a/test/random_matrix_helper.h
+++ b/test/random_matrix_helper.h
@@ -39,6 +39,9 @@
 template <typename VectorType, typename RealScalar>
 VectorType setupRangeSvs(const Index dim, const RealScalar min, const RealScalar max);
 
+template <typename MatrixType>
+void setRandomWellConditionedDiagonal(MatrixType& m);
+
 }  // end namespace Eigen
 
 #endif  // EIGEN_COMP_ICC
@@ -238,6 +241,35 @@
   return min * (VectorType::Ones(dim) - svs) + max * svs;
 }
 
+/**
+ * Overwrites the diagonal of a matrix with random entries of modulus in [1/2, 1],
+ * leaving the other entries untouched.
+ *
+ * For a diagonal matrix built this way the condition number is at most 2 and
+ * `|det| >= 2^-dim`, which is what makes a determinant check against the product of
+ * the entries meaningful. Drawing unconstrained entries instead leaves the
+ * conditioning unbounded. For real scalars, the smallest magnitude among `dim`
+ * uniform draws from [-1, 1) falls below the `4*dim*eps*maxPivot` rank threshold
+ * with probability about `4*dim^2*eps` when `maxPivot` is of order one. Complex
+ * draws use independent real and imaginary components, so their near-zero
+ * probability is quadratic in the threshold, but they can likewise make the
+ * determinant check ill-conditioned.
+ *
+ * @tparam MatrixType type of the matrix whose diagonal is set
+ * @param m matrix whose diagonal is overwritten
+ */
+template <typename MatrixType>
+void setRandomWellConditionedDiagonal(MatrixType& m) {
+  using Scalar = typename MatrixType::Scalar;
+  using RealScalar = typename NumTraits<Scalar>::Real;
+  for (Index i = 0; i < m.diagonalSize(); ++i) {
+    // numext::sign is the unit-modulus phase for complex scalars and +-1 for real ones.
+    const Scalar z = internal::random<Scalar>();
+    const Scalar phase = numext::is_exactly_zero(z) ? Scalar(1) : numext::sign(z);
+    m.diagonal()(i) = phase * internal::random<RealScalar>(RealScalar(0.5), RealScalar(1));
+  }
+}
+
 }  // end namespace Eigen
 
 template <typename DataContainer>