feat: inverse() math utility added

Relates to #268
This commit is contained in:
Mateusz Pusz
2023-09-20 20:13:39 +02:00
parent becca905e7
commit f9ffacc713
2 changed files with 31 additions and 4 deletions

View File

@@ -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

View File

@@ -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;
@@ -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));
@@ -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