Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up median #665

Merged
merged 1 commit into from
Dec 27, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions numbat/modules/math/statistics.nbt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ fn stdev<D: Dim>(xs: List<D>) -> D = sqrt(variance(xs))
@example("median([1 m, 2 m, 400 cm])")
fn median<D: Dim>(xs: List<D>) -> D = # TODO: this is extremely inefficient
if mod(n, 2) == 1
then element_at((n - 1) / 2, sort(xs))
else mean([element_at(n / 2 - 1, sort(xs)), element_at(n / 2, sort(xs))])
then element_at((n - 1) / 2, sorted)
else (element_at(n / 2 - 1, sorted) + element_at(n / 2, sorted)) / 2
where
n = len(xs)
and sorted = sort(xs)
9 changes: 3 additions & 6 deletions numbat/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,9 @@ impl<T: Clone> NumbatList<T> {
/// clone the value that's being returned.
pub fn head(self) -> Option<T> {
let front = self.view.map_or(0, |(start, _end)| start);
if Arc::strong_count(&self.alloc) == 1 {
// safety: unwrap cannot fail because we ensured there was only one strong reference above
let mut alloc = Arc::try_unwrap(self.alloc).map_err(|_| ()).unwrap();
alloc.swap_remove_front(front)
} else {
self.alloc.get(front).cloned()
match Arc::try_unwrap(self.alloc) {
Ok(mut solely_owned) => solely_owned.swap_remove_front(front),
Err(shared) => shared.get(front).cloned(),
}
}

Expand Down
Loading