rust-num / num-complex

Complex numbers for Rust
Apache License 2.0
232 stars 50 forks source link

cast between complex return None #93

Open serendipity-crypto opened 3 years ago

serendipity-crypto commented 3 years ago

I am writing a function, which uses the cast between "Complex" and other "Num"s such as "u64, f64, Complex". The cast between "Complex" and primitive will be correct. But how can I easily cast between "Complex" and "Complex"? 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);
cuviper commented 3 years ago

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.

serendipity-crypto commented 3 years ago

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

Rikorose commented 2 years ago

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;