num-complex icon indicating copy to clipboard operation
num-complex copied to clipboard

cast between complex return None

Open serendipity-crypto opened this issue 4 years ago • 3 comments

I am writing a function, which uses the cast between "Complex<T>" and other "Num"s such as "u64, f64, Complex<U>". The cast between "Complex<T>" and primitive will be correct. But how can I easily cast between "Complex<T>" and "Complex<U>"? This always return a "None" and leads panic.

    let a: Complex64;
    let b: Complex64 = Complex64 { re: (1.), im: (2.) };
    a = cast::<Complex64, Complex64>(b).unwrap();
    println!("{}", a);

serendipity-crypto avatar Jul 23 '21 08:07 serendipity-crypto

Hmm, NumCast won't work because it goes through ToPrimitive, so you get None when there's an imaginary part.

I think we would ideally implement something like TryFrom<Complex<U>> for Complex<T> where T: TryFrom<U>, but that will probably conflict with the reflexive case, T = U. That leaves us with manually (or by macro) expanding a bunch of combinations, which is gross, but possible. Or we could just add a direct conversion method on Complex itself.

cuviper avatar Jul 23 '21 15:07 cuviper

Thanks for your idea. I will try to implement direct conversion method on Complex later. :blush:

serendipity-crypto avatar Jul 23 '21 15:07 serendipity-crypto

Hi, not sure what the current state is, but casting a complex value to a higher precision would be nice to have (like f32 as f64):

let a = Complex32{re: 1., im: 1.};
let b = a as Complex64;

Rikorose avatar Aug 11 '22 08:08 Rikorose