Skip to content

Commit

Permalink
Add fma to math.h
Browse files Browse the repository at this point in the history
  • Loading branch information
NAThompson committed Dec 9, 2023
1 parent 173c500 commit 50443df
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/utility/include/mp-units/math.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,27 @@ template<auto R, typename Rep>
return {static_cast<Rep>(abs(q.numerical_value_ref_in(q.unit))), R};
}

/**
* @brief Computes the fma of 3 quantities
*
* @param a: Multiplicand
* @param x: Multiplicand
* @param b: Addend
* @return Quantity: The nearest floating point representable to ax+b
*/
template<auto R, auto S, typename Rep>
[[nodiscard]] constexpr quantity<R, Rep> fma(const quantity<R, Rep>& a, const quantity<S, Rep>& x,
const quantity<R, Rep>& b) noexcept
requires requires { fma(a.numerical_value_ref_in(a.unit)); } ||
requires { std::fma(a.numerical_value_ref_in(a.unit)); }
{
using std::fma;
return {static_cast<Rep>(
fma(a.numerical_value_ref_in(a.unit), x.numerical_value_ref_in(x.unit), b.numerical_value_ref_in(b.unit))),
R};
}


/**
* @brief Returns the epsilon of the quantity
*
Expand Down
6 changes: 6 additions & 0 deletions test/unit_test/runtime/math_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ TEST_CASE("'cbrt()' on quantity changes the value and the dimension accordingly"
REQUIRE(cbrt(8 * isq::volume[m3]) == 2 * isq::length[m]);
}

TEST_CASE("'fma()' on quantity changes the value and the dimension accordingly", "[math][cbrt]")
{
REQUIRE(fma(1.0 * isq::length[m], 2.0, 2.0 * isq::length[m]) == 4.0 * isq::length[m]);
}


TEST_CASE("'pow<Num, Den>()' on quantity changes the value and the dimension accordingly", "[math][pow]")
{
REQUIRE(pow<1, 4>(16 * isq::area[m2]) == sqrt(4 * isq::length[m]));
Expand Down
5 changes: 5 additions & 0 deletions test/unit_test/static/math_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ template<typename T1, typename T2, typename... Ts>

#if __cpp_lib_constexpr_cmath || MP_UNITS_COMP_GCC

static_assert(compare(fma(2 * m, 3 * m, 1 * m2), 7 * m2));
static_assert(compare(fma(2.0 * s, 3.0 * Hz, 1.0), 7.0));
static_assert(compare(fma(2 * s, 3 * Hz, 1), 7));
static_assert(compare(fma(2.0, 3.0*m, 1.0*m), 7*m);
static_assert(compare(fma(2.0*m, 3.0, 1.0*m), 7*m));
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

0 comments on commit 50443df

Please sign in to comment.