Взаимозаменяемо ли сложение x + x
на умножение 2 * x
в стандарте IEEE 754 (IEC 559) с плавающей запятой или, в более общем смысле, есть ли гарантия, что case_add
и case_mul
всегда дают точно тот же результат?
#include <limits>
template <typename T>
T case_add(T x, size_t n)
{
static_assert(std::numeric_limits<T>::is_iec559, "invalid type");
T result(x);
for (size_t i = 1; i < n; ++i)
{
result += x;
}
return result;
}
template <typename T>
T case_mul(T x, size_t n)
{
static_assert(std::numeric_limits<T>::is_iec559, "invalid type");
return x * static_cast<T>(n);
}