Last active
July 11, 2024 20:45
-
-
Save pallas/5565528 to your computer and use it in GitHub Desktop.
Minkowski distance function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// All rights reserved, | |
// Derrick Pallas | |
// License: zlib | |
#include <cmath> | |
#include <cstdlib> | |
#include <limits> | |
#include <vector> | |
template <typename fp_type> | |
fp_type minkowski_distance(const fp_type & p, const std::vector<fp_type> & ds) { | |
// ds contains d[i] = v[i] - w[i] for two vectors v and w | |
fp_type ex = 0.0; | |
fp_type min_d = std::numeric_limits<fp_type>::infinity(); | |
fp_type max_d = -std::numeric_limits<fp_type>::infinity(); | |
for (int i = 0 ; i < ds.size() ; ++i) { | |
fp_type d = std::fabs(ds[i]); | |
ex += std::pow(d, p); | |
min_d = std::min(min_d, d); | |
max_d = std::max(max_d, d); | |
} | |
return std::isnan(ex) ? ex | |
: !std::isnormal(ex) && std::signbit(p) ? min_d | |
: !std::isnormal(ex) && !std::signbit(p) ? max_d | |
: std::pow(ex, 1.0/p); | |
} | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
p may not be the same type as ds