Skip to content

Instantly share code, notes, and snippets.

@pallas
Last active July 11, 2024 20:45
Show Gist options
  • Save pallas/5565528 to your computer and use it in GitHub Desktop.
Save pallas/5565528 to your computer and use it in GitHub Desktop.
Minkowski distance function
// 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);
}
//
@ecs-abdulgkhan
Copy link

p may not be the same type as ds

@Geeky-Sam01
Copy link

nice code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment