I have a matrix that I want to print for debugging purposes. Running using the Display trait generally gives nice output, but sometimes, when my values are arbitrary, the matrix becomes super wide, line breaks, and becomes ugly.
let A: SMatrix<f64,Const<4>,Const<4>,...> = ... // exact computation omitted
eprintln!("{}",A);
in my case returns
┌ ┐
│ -1.4142135623730947 -0.00000000000000016653345369377348 -0.000000000000000000000000000000045550777770751173 -0.0000000000000002051424657947912 │
│ 0 1.4142135623730943 -0.000000000000000000000000000000018867749929288036 -0.00000000000000008497279155086128 │
│ 0 0 0.9999999999999996 -0.9999999999999994 │
│ 0 0 0 -0.9999999999999994 │
└ ┘
This is nice output sometimes when the values don't have too many decimals, but the precision in my f64 elements sometimes makes the printed output very very wide (like in the above example. With line breaks in the terminal, the output becomes unreadable.
In numpy, I'm used to setting a global option for print precision, or using a context manager to give a local option for it. I could imagine rounding before print, like eprintln!("{}",my_matrix.simdd_round(2);
but this fails, reporting that I need a complex matrix for simd rounding to work.
How can I print a matrix with specified precision, in nalgebra
for rust?
You can simply pass the precision in your eprintln!
invocation:
use nalgebra::SMatrix;
fn main() {
#[rustfmt::skip]
let a = SMatrix::<f32, 4, 4>::new(
-1.4142135623730947, -0.00000000000000016653345369377348, -0.000000000000000000000000000000045550777770751173, -0.0000000000000002051424657947912,
0.0 , 1.4142135623730943 , -0.000000000000000000000000000000018867749929288036, -0.00000000000000008497279155086128,
0.0 , 0.0 , 0.9999999999999996 , -0.9999999999999994,
0.0 , 0.0 , 0.0 , -0.9999999999999994,
); ;
eprintln!("{a:.2}");
}
will print
┌ ┐
│ -1.41 -0.00 -0.00 -0.00 │
│ 0.00 1.41 -0.00 -0.00 │
│ 0.00 0.00 1.00 -1.00 │
│ 0.00 0.00 0.00 -1.00 │
└ ┘