Skip to content

Commit

Permalink
feat: inverse() math utility added
Browse files Browse the repository at this point in the history
Relates to #268
  • Loading branch information
mpusz committed Sep 20, 2023
1 parent becca90 commit f9ffacc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
13 changes: 13 additions & 0 deletions src/utility/include/mp-units/math.h
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,19 @@ template<Unit auto To, auto R, typename Rep>
}
}

/**
* @brief Computes the inverse of a quantity in a provided unit
*/
template<Unit auto To, auto R, typename Rep>
[[nodiscard]] constexpr QuantityOf<dimensionless / get_quantity_spec(R)> auto inverse(const quantity<R, Rep>& q)
requires requires {
quantity_values<Rep>::one();
value_cast<To>(1 / q);
}
{
return (quantity_values<Rep>::one() * one).force_in(To * q.unit) / q;
}

/**
* @brief Computes the square root of the sum of the squares of x and y,
* without undue overflow or underflow at intermediate stages of the computation
Expand Down
22 changes: 18 additions & 4 deletions test/unit_test/static/math_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@
#include <mp-units/systems/si/unit_symbols.h>
#include <optional>

#if __cpp_lib_constexpr_cmath || MP_UNITS_COMP_GCC

namespace {

using namespace mp_units;
Expand All @@ -40,6 +38,8 @@ template<typename T1, typename T2, typename... Ts>
return is_same_v<T1, T2> && v1 == v2 && (... && (v1 == vs));
}

#if __cpp_lib_constexpr_cmath || MP_UNITS_COMP_GCC

static_assert(compare(pow<0>(2 * m), 1 * one));
static_assert(compare(pow<1>(2 * m), 2 * m));
static_assert(compare(pow<2>(2 * m), 4 * pow<2>(m), 4 * m2));
Expand Down Expand Up @@ -201,6 +201,20 @@ static_assert(compare(round<si::second>(-1499. * isq::time[ms]), -1. * isq::time
static_assert(compare(round<si::second>(-1500. * isq::time[ms]), -2. * isq::time[s]));
static_assert(compare(round<si::second>(-1999. * isq::time[ms]), -2. * isq::time[s]));

} // namespace

#endif

// non-truncating
static_assert(compare(inverse<us>(250 * Hz), 4000 * us));
static_assert(compare(inverse<us>(250 * kHz), 4 * us));
static_assert(compare(inverse<ks>(250 * uHz), 4 * ks));

// truncating
static_assert(compare(inverse<s>(1 * kHz), 0 * s));

// floating-point representation does not truncate
static_assert(compare(inverse<s>(1. * kHz), 0.001 * s));

// check if constraints work properly for a derived unit of a narrowed kind
static_assert(compare(inverse<Hz>(1 * s), 1 * Hz));

} // namespace

0 comments on commit f9ffacc

Please sign in to comment.