Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
13 changes: 10 additions & 3 deletions src/quantile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub mod interpolate {
use ndarray::azip;
use ndarray::prelude::*;
use num_traits::{FromPrimitive, ToPrimitive};
use std::ops::{Add, Div};
use std::ops::{Add, Div, Sub};

/// Used to provide an interpolation strategy to [`quantile_axis_mut`].
///
Expand Down Expand Up @@ -116,7 +116,7 @@ pub mod interpolate {

impl<T> Interpolate<T> for Midpoint
where
T: Add<T, Output = T> + Div<T, Output = T> + Clone + FromPrimitive,
T: Add<T, Output = T> + Sub<T, Output=T> + Div<T, Output = T> + Clone + FromPrimitive,
{
fn needs_lower(_q: f64, _len: usize) -> bool {
true
Expand All @@ -134,7 +134,14 @@ pub mod interpolate {
D: Dimension,
{
let denom = T::from_u8(2).unwrap();
(lower.unwrap() + higher.unwrap()).mapv_into(|x| x / denom.clone())
let mut lower = lower.unwrap();
let higher = higher.unwrap();
azip!(
mut lower, ref higher in {
*lower = lower.clone() + (higher.clone() - lower.clone()) / denom.clone()
}
);
lower
}
}

Expand Down
11 changes: 11 additions & 0 deletions tests/quantile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use ndarray::prelude::*;
use ndarray_stats::{
interpolate::{Higher, Linear, Lower, Midpoint, Nearest},
QuantileExt,
Quantile1dExt,
};

#[test]
Expand Down Expand Up @@ -148,3 +149,13 @@ fn test_quantile_axis_skipnan_mut_linear_opt_i32() {
assert_eq!(q[0], Some(3));
assert!(q[1].is_none());
}

#[test]
fn test_midpoint_overflow() {
// Regression test
// This triggered an overflow panic with a naive Midpoint implementation: (a+b)/2
let mut a: Array1<u8> = array![129, 130, 130, 131];
let median = a.quantile_mut::<Midpoint>(0.5).unwrap();
let expected_median = 130;
assert_eq!(median, expected_median);
}