Math#

Defined in namespace hal

#include <libhal-util/math.hpp>

group Math

Functions

template<typename T>
std::optional<T> multiply(T p_lhs, T p_rhs)#

Perform multiply operation and return an error code std::errc::result_out_of_range if the two values when multiplied would overflow the containing value.

Template Parameters:

T – - integer arithmetic type

Parameters:
  • p_lhs – - left hand side integer

  • p_rhs – - right hand side integer

Returns:

std::optional<T> - the resultant, std::nullopt if the operation overflows.

template<typename T>
constexpr T absolute_value(T p_value) noexcept#

Generic absolute value function that works for integer types.

Preferred this over the C API for rounding numbers such as abs(), labs() and llabs(). This function relieves the need in template code to check the type of the integer and select the correct function to call.

NOTE: If p_value is minimum negative number of type T then the resulting return value will be the maximum positive number represented by T. For example, INT32_MIN is 2147483648 where as INT32_MAX is 2147483647. The absolute value of INT32_MIN is 1 greater than INT32_MAX. To prevent overflow, passing INT32_MIN will simply return back INT32_MAX.

Template Parameters:

T – - integral type

Parameters:

p_value – - integer value to be made positive

Returns:

T - positive representation of the integer

template<typename T>
constexpr T rounding_division(T p_numerator, T p_denominator)#

Perform integer division and round the value up if the next decimal place is greater than or equal to 0.5.

Template Parameters:

T – - integral type of the two operands

Parameters:
  • p_numerator – - the value to be divided

  • p_denominator – - the value to divide the numerator against

Returns:

T - rounded quotient between numerator and denominator. Returns 0 if the denominator is greater than the numerator.

template<typename T>
constexpr T distance(T p_left, T p_right)#

Calculates the distance between two values (L1 Norm or Manhattan distance), the absolute value of their difference.

Template Parameters:

T – - integral type of the two values

Parameters:
  • p_left – - the first point of the distance calculation

  • p_right – - the second point of the distance calculation

Returns:

constexpr T - absolute value of the difference between the two points.

constexpr bool equals(std::floating_point auto p_value1, std::floating_point auto p_value2, float p_epsilon = 1e-9f)#

Determines if two values are equal within a relative error.

Parameters:
  • p_value1 – - First value to compare.

  • p_value2 – - Second value to compare.

  • p_epsilon – - Error margin that the difference is compared to.

Returns:

true - difference is less than epsilon

Returns:

false - difference is more than epsilon