I am trying to make an is_integer
template function to determine a number is an integer or not.
The experimental implementation
is_integer
Template Function Implementationtemplate<typename T, typename TestT = double> constexpr bool is_integer(T input) { TestT floor_input = std::floor(static_cast<TestT>(input)); if (std::abs(floor_input - input) <= std::numeric_limits<T>::epsilon() ) { return true; } return false; }
Full Testing Code
The full testing code:
// An is_integer Template Function Implementation in C++
#include <cassert>
#include <chrono>
#include <cmath>
#include <iostream>
#include <vector>
template<typename T, typename TestT = double>
constexpr bool is_integer(T input)
{
TestT floor_input = std::floor(static_cast<TestT>(input));
if (std::abs(floor_input - input) <= std::numeric_limits<T>::epsilon() )
{
return true;
}
return false;
}
void isIntegerTest();
int main()
{
auto start = std::chrono::system_clock::now();
isIntegerTest();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
}
void isIntegerTest()
{
assert(is_integer(1) == true);
assert(is_integer(2) == true);
assert(is_integer(3) == true);
assert(is_integer(1.1) == false);
float test_number1 = 1.2;
assert(is_integer(test_number1) == false);
test_number1 = 1;
assert(is_integer(test_number1) == true);
double test_number2 = 2;
assert(is_integer(test_number2) == true);
test_number2 = 2.0001;
assert(is_integer(test_number2) == false);
return;
}
All suggestions are welcome.