ndarray icon indicating copy to clipboard operation
ndarray copied to clipboard

Dot product with complex numbers

Open klangner opened this issue 8 years ago • 5 comments

It looks that dot() function gives wrong result when used with complex numbers:

What I would expect:

let xs = Array::from_vec(vec![Complex::new(1., 1.), Complex::new(3., -1.)]);
assert!(xs.dot(&xs) == 12.);

What I get:

Complex { re: 8, im: -4 }

Dot product should never be a complex number. Is this bug or this function means something else?

klangner avatar Mar 02 '17 14:03 klangner

It's documented to be like that, so it's intentional.

https://docs.rs/ndarray/0.7.3/ndarray/struct.ArrayBase.html#method.dot

The traits can also give away the fact that there is no way for the implementation to conjugate.

bluss avatar Mar 02 '17 14:03 bluss

I see. Do you think it make sense to add new a function inner_product() to this library? Or it is rather out of scope for this library?

BTW: I know I can implement it like this (Or maybe better, I'm new to Rust :-) ):

pub fn inner_product(v1: &Array<Complex64, Ix1>, v2: &Array<Complex64, Ix1>) -> Complexf64 {
    let vs: Vector = v2.iter().map(|x| x.conj()).collect();
    v1.dot(&vs)
}

Anyway. Thanks for the fast respond!

EDIT: Fixed return type.

klangner avatar Mar 02 '17 14:03 klangner

It does make sense to add it, since we have explicit support for Complex as scalars

bluss avatar Mar 02 '17 14:03 bluss

The main design issues here are actually around numeric traits. I'm not fond of the status quo.

My ideal “complex” trait would have floats and Complex both implement the same complex trait. Real numbers are part of C.

bluss avatar Mar 31 '17 17:03 bluss

I have an implementation for Complex double precision floating point here based on the existing code: https://github.com/BQSKit/bqskitrs/blob/272698ca38b000e8b830fcc441e27e4a5d96489c/squaremat/src/matmul.rs#L14

I'd be happy to upstream this code in some form. I agree the numeric traits are not ideal :/

emmatyping avatar Nov 06 '21 00:11 emmatyping