1 #ifndef STAN_MATH_PRIM_FUN_DISTANCE_HPP
2 #define STAN_MATH_PRIM_FUN_DISTANCE_HPP
3 
4 #include <stan/math/prim/meta.hpp>
5 #include <stan/math/prim/err.hpp>
6 #include <stan/math/prim/fun/abs.hpp>
7 #include <stan/math/prim/fun/Eigen.hpp>
8 #include <stan/math/prim/fun/squared_distance.hpp>
9 #include <stan/math/prim/fun/sqrt.hpp>
10 #include <cmath>
11 
12 namespace stan {
13 namespace math {
14 
15 /**
16  * Returns the distance between two scalars.
17  *
18  * @tparam T1 type of first scalar.
19  * @tparam T2 type of second scalar
20  * @param x1 First scalar.
21  * @param x2 Second scalar.
22  * @return Distance between two scalars
23  * @throw std::domain_error If the arguments are not finite.
24  */
25 template <typename T1, typename T2,
26           require_all_stan_scalar_t<T1, T2>* = nullptr>
distance(const T1 & x1,const T2 & x2)27 inline return_type_t<T1, T2> distance(const T1& x1, const T2& x2) {
28   check_finite("distance", "x1", x1);
29   check_finite("distance", "x2", x2);
30   return abs(x1 - x2);
31 }
32 
33 /**
34  * Returns the distance between the specified vectors.
35  *
36  * @tparam T1 type of the first vector (must be derived from \c
37  * Eigen::MatrixBase and have one compile time dimension equal to 1)
38  * @tparam T2 type of the second vector (must be derived from \c
39  * Eigen::MatrixBase and have one compile time dimension equal to 1)
40  * @param x1 First vector.
41  * @param x2 Second vector.
42  * @return Distance between the vectors.
43  * @throw std::domain_error If the vectors are not the same
44  * size.
45  */
46 template <typename T1, typename T2, require_all_vector_t<T1, T2>* = nullptr>
distance(const T1 & x1,const T2 & x2)47 inline return_type_t<T1, T2> distance(const T1& x1, const T2& x2) {
48   using std::sqrt;
49   check_matching_sizes("distance", "x1", x1, "x2", x2);
50   return sqrt(squared_distance(x1, x2));
51 }
52 
53 }  // namespace math
54 }  // namespace stan
55 
56 #endif
57