Skip to content

Generic conversion of real constants into ComplexFloat #140

Open
@grothesque

Description

@grothesque

In generic complex code it is common to have to convert real values into T: ComplexFloat. For this, I find the following trait very handy:

pub trait IntoComplex<T: ComplexFloat> {
    fn into_complex(self) -> T;
}

impl<T> IntoComplex<T> for f32
where
    T: ComplexFloat,
    f32: Into<T::Real>,
    T::Real: Into<T>,
{
    fn into_complex(self) -> T {
        self.into().into()
    }
}

It allows to write

fn some_calculation<T>(x: T) -> T
where
    T: ComplexFloat + NumAssign,
    f32: IntoComplex<T>,
{
    let a = 2.0.into_complex();
    let b = 3.0.into_complex();
    let mut sum: T = 0.0.into_complex();
    sum += x * a + b;
    sum *= b;
    sum
}

instead of

fn some_calculation<T>(x: T) -> T
where
    T: ComplexFloat + NumAssign,
    f32: Into<T::Real>,
    T::Real: Into<T>,
{
    let a = 2.0.into().into();
    let b = 3.0.into().into();
    let mut sum: T = 0.0.into().into();
    sum += x * a + b;
    sum *= b;
    sum
}

I am aware of num_traits::cast but those casts can fail and they can involve information loss.

In contrast, the IntoComplex conversion always works and preserves all information. This is also why using it involves less boilerplate.

How about adding something along these lines to this crate?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions