ndarray icon indicating copy to clipboard operation
ndarray copied to clipboard

Provide element-wise math functions for floats

Open KmolYuan opened this issue 4 years ago • 0 comments

This is an improvement to reduce Array::mapv calling.

use num_traits::Float;

// For Array<Float>
impl<A, S, D> ArrayBase<S, D>
where
    A: Float,
    S: RawData<Elem = A>,
    D: Dimension,
{
    pub fn square(&self) -> Array<A, D> {
        self.mapv(|v| v * v)
    }
    pub fn sqrt(&self) -> Array<A, D> {
        self.mapv(A::sqrt)
    }
    // abs, pow, sin, cos, round, ceil, etc.
    ...
}

The following is a little part of my code, a lot of mappings were used here. (solved by a local plug-in trait)

let dt = dxy.square().sum_axis(Axis(1)).sqrt();
let phi_n = &phi * n as f64;
let cos_phi_n = (phi_n.slice(s![1..]).cos() - phi_n.slice(s![..-1]).cos()) / &dt;
let sin_phi_n = (phi_n.slice(s![1..]).sin() - phi_n.slice(s![..-1]).sin()) / &dt;

I hope it can be officially supported.

KmolYuan avatar May 06 '21 03:05 KmolYuan