The easy way to calculate euclidean distances in Stan (for 2D points)

138 views
Skip to first unread message

Bob K

unread,
Apr 21, 2017, 9:12:13 AM4/21/17
to Stan users mailing list
This isn't a question, just an answer I found that I wanted to share.

I'm working on a model that heavily uses euclidean distances, which lend some awkwardness to the code. BUT, at some point in time (or maybe I missed it), the Stan team added a hypotenuse function (hypot(), page 423), that calculates the following function for two reals (x,y) --> sqrt( x^2 + y^2). So it only works for 2-D points, and it isn't vectorized, but still, a time-saver.

OK, commercial over... Just wanted to post this in case anyone has a similar coding issue.

Daniel Lee

unread,
Apr 21, 2017, 9:27:52 AM4/21/17
to stan-...@googlegroups.com
There is also the distance() and squared_distance() functions. 

I believe those are vectorized (and the manual's signature for those functions aren't correct, but I'll have to double check the code to verify). 


Daniel
--
You received this message because you are subscribed to the Google Groups "Stan users mailing list" group.
To unsubscribe from this group and stop receiving emails from it, send an email to stan-users+...@googlegroups.com.
To post to this group, send email to stan-...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Bob K

unread,
Apr 21, 2017, 9:37:35 AM4/21/17
to Stan users mailing list
OH cool so distance is hypot vectorized. Very nice.

What we would be even more awesome is to have it loop over dimensions by defining a matrix function, but of course it's not hard to nest the distance function in a per-dimension summation loop.

Bob Carpenter

unread,
Apr 21, 2017, 4:02:37 PM4/21/17
to stan-...@googlegroups.com
Version 1.0 --- it's built into C, and we started with all
the C/C++ library functions. Only got into C++ in C++11:

http://www.cplusplus.com/reference/cmath/hypot/

- Bob

> On Apr 21, 2017, at 9:12 AM, Bob K <bobku...@gmail.com> wrote:
>

Bob Carpenter

unread,
Apr 21, 2017, 4:03:37 PM4/21/17
to stan-...@googlegroups.com
I think we'd do general maps before we started adding
a bunch of customization for particular functions. Maybe
in a couple years---C++11 makes a lot of the higher-order
stuff much much easier with closures.

- Bob
Reply all
Reply to author
Forward
0 new messages