aboutsummaryrefslogtreecommitdiffstats
path: root/src/utility/LinearApproximation.h
diff options
context:
space:
mode:
authorFinlay Davidson <finlay.davidson@coderclass.nl>2023-03-16 21:46:16 +0100
committerRiku Isokoski <riksu9000@gmail.com>2023-03-27 22:12:32 +0000
commit2ba8b179679aa92be46ac7688542b68f2695e04d (patch)
tree5f207515c6391529beb2182cbb3f6df47e5943f6 /src/utility/LinearApproximation.h
parent9641fd7308208442680a93350f22b3e59082c95c (diff)
linearapproximation: Move to src/utility
Diffstat (limited to 'src/utility/LinearApproximation.h')
-rw-r--r--src/utility/LinearApproximation.h41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/utility/LinearApproximation.h b/src/utility/LinearApproximation.h
new file mode 100644
index 00000000..34ceb7f2
--- /dev/null
+++ b/src/utility/LinearApproximation.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <cstddef>
+#include <array>
+
+namespace Pinetime {
+ namespace Utility {
+ // based on: https://github.com/SHristov92/LinearApproximation/blob/main/Linear.h
+ template <typename Key, typename Value, std::size_t Size>
+ class LinearApproximation {
+ using Point = struct {
+ Key key;
+ Value value;
+ };
+
+ public:
+ LinearApproximation(const std::array<Point, Size>&& sorted_points) : points {sorted_points} {
+ }
+
+ Value GetValue(Key key) const {
+ if (key <= points[0].key) {
+ return points[0].value;
+ }
+
+ for (std::size_t i = 1; i < Size; i++) {
+ const auto& p = points[i];
+ const auto& p_prev = points[i - 1];
+
+ if (key < p.key) {
+ return p_prev.value + (key - p_prev.key) * (p.value - p_prev.value) / (p.key - p_prev.key);
+ }
+ }
+
+ return points[Size - 1].value;
+ }
+
+ private:
+ std::array<Point, Size> points;
+ };
+ }
+}