rust-num / num-complex

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

Added ability to sort Complex numbers. #107

Closed annoybot closed 2 years ago

annoybot commented 2 years ago

Why?

I have a lot of unit tests to write which need to check arrays of complex numbers.

Being able to sort an array of Complex, makes it easier to write these tests (I can just sort the actual results and the expected results and compare).

bluss commented 2 years ago

This change means that complex can now be used with operators such as <, <=, which needs some rationale, is there a good reason?

annoybot commented 2 years ago

Indeed the complex numbers are not an ordered field, so as you point out the < operation makes no mathematical sense for it.

I actually solved my problem in a different way by creating a temporary struct:

    #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default, PartialOrd, Ord)]
    struct CplxSortAdaptor<T:Float> {
        pub re: T,
        pub im: T,
    }

I was then able to write a function sort_lex<F:Float>(list: &mut[Complex<F>]) which copies the list to be sorted into a list of CplxSortAdaptor, sorts it, then copies the results back into list.

Not super efficient, but OK, since it's only needed in my unit tests.

I don't know why I didn't see this solution sooner.

I propose to close this PR for the reasons you cited. Thanks for your feedback.

cuviper commented 2 years ago

Closing, but we can follow up on how to use custom sorting in #106.