Skip to content
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/numeric/impl_numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,84 @@ impl<A, S, D> ArrayBase<S, D>
sum
}

/// Return a reference to a maximum of all values.
/// Return None if a comparison fails or if self is empty.
///
/// # Example
/// ```
/// use ndarray::arr2;
/// use std::f64;
///
/// let a = arr2(&[[1., 2.], [3., 4.]]);
///
/// assert_eq!(a.scalar_max(), Some(&4.));
///
/// let b = arr2(&[[1., f64::NAN], [3., 4.]]);
///
/// assert_eq!(b.scalar_max(), None);
/// ```
pub fn scalar_max(&self) -> Option<&A>
where A: PartialOrd
{
if let Some(slc) = self.as_slice_memory_order() {
let mut max = self.first();
for item in slc.iter().skip(1) {
match max.partial_cmp(&Some(item)) {
None => return None,
Some(::std::cmp::Ordering::Less) => max = Some(item),
_ => {},
}
}
max
} else {
Zip::from(self).fold_while(self.first(), |acc, x|
match acc.partial_cmp(&Some(x)) {
None => FoldWhile::Done(None),
Some(::std::cmp::Ordering::Less) => FoldWhile::Continue(Some(x)),
_ => FoldWhile::Continue(acc),
}).into_inner()
}
}

/// Return a reference to a minimum of all values.
/// Return None if a comparison fails or if self is empty.
///
/// # Example
/// ```
/// use ndarray::arr2;
/// use std::f64;
///
/// let a = arr2(&[[1., 2.], [3., 4.]]);
///
/// assert_eq!(a.scalar_min(), Some(&1.));
///
/// let b = arr2(&[[1., f64::NAN], [3., 4.]]);
///
/// assert_eq!(b.scalar_min(), None);
/// ```
pub fn scalar_min(&self) -> Option<&A>
where A: PartialOrd
{
if let Some(slc) = self.as_slice_memory_order() {
let mut min = self.first();
for item in slc.iter().skip(1) {
match min.partial_cmp(&Some(item)) {
None => return None,
Some(::std::cmp::Ordering::Greater) => min = Some(item),
_ => {},
}
}
min
} else {
Zip::from(self).fold_while(self.first(), |acc, x|
match acc.partial_cmp(&Some(x)) {
None => FoldWhile::Done(None),
Some(::std::cmp::Ordering::Greater) => FoldWhile::Continue(Some(x)),
_ => FoldWhile::Continue(acc),
}).into_inner()
}
}

/// Return sum along `axis`.
///
/// ```
Expand Down