Clustering
C++20 header-only: DBSCAN, HDBSCAN, k-means.
Loading...
Searching...
No Matches
equality.h
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <cmath>
5#include <cstddef>
6#include <utility>
7
9
10namespace clustering::math {
11
28template <class T, std::size_t N, Layout LA, Layout LB>
29bool arrayEqual(const NDArray<T, N, LA> &a, const NDArray<T, N, LB> &b) noexcept {
30 std::array<std::size_t, N> shape{};
31 std::size_t total = 1;
32 for (std::size_t k = 0; k < N; ++k) {
33 if (a.dim(k) != b.dim(k)) {
34 return false;
35 }
36 shape[k] = a.dim(k);
37 total *= shape[k];
38 }
39 if (total == 0) {
40 return true;
41 }
42 std::array<std::size_t, N> idx{};
43 for (std::size_t flat = 0; flat < total; ++flat) {
44 const bool equal = [&]<std::size_t... Ks>(std::index_sequence<Ks...>) {
45 return a(idx[Ks]...) == b(idx[Ks]...);
46 }(std::make_index_sequence<N>{});
47 if (!equal) {
48 return false;
49 }
50 for (std::size_t k = N; k-- > 0;) {
51 if (++idx[k] < shape[k]) {
52 break;
53 }
54 idx[k] = 0;
55 }
56 }
57 return true;
58}
59
77template <class T, std::size_t N, Layout LA, Layout LB>
78bool allClose(const NDArray<T, N, LA> &a, const NDArray<T, N, LB> &b, T rtol = T(1e-5),
79 T atol = T(1e-8)) noexcept {
80 std::array<std::size_t, N> shape{};
81 std::size_t total = 1;
82 for (std::size_t k = 0; k < N; ++k) {
83 if (a.dim(k) != b.dim(k)) {
84 return false;
85 }
86 shape[k] = a.dim(k);
87 total *= shape[k];
88 }
89 if (total == 0) {
90 return true;
91 }
92 std::array<std::size_t, N> idx{};
93 for (std::size_t flat = 0; flat < total; ++flat) {
94 auto [va, vb] = [&]<std::size_t... Ks>(std::index_sequence<Ks...>) {
95 return std::pair<T, T>{a(idx[Ks]...), b(idx[Ks]...)};
96 }(std::make_index_sequence<N>{});
97 const T diff = std::fabs(va - vb);
98 const T tol = atol + (rtol * std::fabs(vb));
99 if (!(diff <= tol)) {
100 return false;
101 }
102 for (std::size_t k = N; k-- > 0;) {
103 if (++idx[k] < shape[k]) {
104 break;
105 }
106 idx[k] = 0;
107 }
108 }
109 return true;
110}
111
112} // namespace clustering::math
Represents a multidimensional array (NDArray) of a fixed number of dimensions N and element type T.
Definition ndarray.h:136
size_t dim(std::size_t index) const noexcept
Returns the size of a specific dimension of the NDArray.
Definition ndarray.h:461
bool allClose(const NDArray< T, N, LA > &a, const NDArray< T, N, LB > &b, T rtol=T(1e-5), T atol=T(1e-8)) noexcept
Element-wise approximate equality with NumPy-style asymmetric tolerance.
Definition equality.h:78
bool arrayEqual(const NDArray< T, N, LA > &a, const NDArray< T, N, LB > &b) noexcept
Element-wise exact equality between two NDArrays of matching shape.
Definition equality.h:29