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

Euclidean distance in "High performance functions with Rcpp" #627

Closed
djhshih opened this issue Nov 26, 2014 · 1 comment
Closed

Euclidean distance in "High performance functions with Rcpp" #627

djhshih opened this issue Nov 26, 2014 · 1 comment

Comments

@djhshih
Copy link

djhshih commented Nov 26, 2014

In this section, the code to calculate "Euclidean distance between a value and a vector of values" is provided as follows:

pdistR <- function(x, ys) {
  sqrt((x - ys) ^ 2)
}

While the code is not incorrect, it is quite inefficient. The square-root and square operations almost effectively cancel out. The euclidean distance between two values x and y in one-dimensional space is simply abs(x - y) and is more efficiently calculated as such. One should probably optimize expressions algebraically before trying to optimize this code with Rcpp.

Given that Euclidean distance is more often used and discussed in spaces with higher than one dimension, a more useful function would probably take a vector input and a matrix input and return a vector output. Perhaps a different example for a vector-input and vector-output function should be used, such as mean-centering a vector:

centerR <- function(ys) {
  ys - mean(ys)
}
@hadley
Copy link
Owner

hadley commented Jan 24, 2017

I agree with your points, but I don't think centerR is an adequate replacement because this example needs a function with a vector argument and a scalar argument.

@hadley hadley closed this as completed Jan 24, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants