sarah-ek / faer-rs

Linear algebra foundation for the Rust programming language
https://faer-rs.github.io
MIT License
1.75k stars 56 forks source link

`Mat::eigenvalues()` may lead to a panic from a failing assertion #110

Closed StHagel closed 4 months ago

StHagel commented 4 months ago

Describe the bug Calling Mat::eigenvalues() may lead to a panic from a failing assertion. To reproduce this, generate a 4096x4096 matrix with random f64 elements of range 0 to 1 and call the eigenvalues funtion (See code below). This will result in the following error:

thread 'main' panicked at /home/sthagel/.cargo/registry/src/index.crates.io-6f17d22bba15001f/faer-0.18.1/src/linalg/evd/hessenberg.rs:816:26:
assertion `left == right` failed: iterators must have the same length
  left: 31
 right: 32
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

To Reproduce

use faer::mat::Mat;
use num::complex::Complex64;
use rand::prelude::*;

fn main() {
    let n = 4096;
    let n_sq = n * n;
    let mat = (0..n_sq)
        .map(|_| {
            let mut rng = rand::thread_rng();
            rng.gen()
        })
        .collect::<Vec<f64>>();
    let results = eigenvals_faer(&mat, n - 2, n);
    println!("{:#?}", results)
}

#[inline]
pub fn eigenvals_faer(
    mat: &[f64],
    nev: usize,
    n: usize,
) -> Result<Vec<Complex64>, &str> {
    if nev * n == 0 || nev > n - 2 {
        return Err("Invalid parameters!");
    }

    let faer_mat: Mat<f64> = Mat::from_fn(n, n, |i, j| mat[i + n * j]);

    let evs = faer_mat.eigenvalues();

    Ok(evs)
}

Expected behavior One would expect the calculation to produce the desired eigenvalues

Desktop (please complete the following information):

Additional info On smaller matrices (e.g. 40x40 instead of 4096x4096) it works just fine.

sarah-ek commented 4 months ago

i'll try to fix this asap

sarah-ek commented 4 months ago

i just published a patch release (0.18.2) that should fix it

StHagel commented 4 months ago

In 0.18.2 it is in fact fixed and works as intended. Thank you for fixing it so quickly :)