Here is the code (python):
def is_integer(num):
if isinstance(num, float):
return num.is_integer()
elif isinstance(num, int):
return True
else:
return False
I'm not sure how returning num.is_integer works and how that makes the function able to distinguish 10.0 from 10.1, as the functions purpose is to determine if the number is unnecessarily made into a float when it should be an int by determining if the number has unnecessary decimal points of 0 as a float. How does returing num.is-integer work to determine if the number has a .0 if the number is a float?
Here is the code as a screenshot
CodePudding user response:
float.is_integer
quite literally just checks if floor(num) == num
.
In other words, it checks if rounding num
down changes its value.
Python3 source code from Github:
float_is_integer_impl(PyObject *self)
/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
{
double x = PyFloat_AsDouble(self);
PyObject *o;
if (x == -1.0 && PyErr_Occurred())
return NULL;
if (!Py_IS_FINITE(x))
Py_RETURN_FALSE;
errno = 0;
o = (floor(x) == x) ? Py_True : Py_False;
if (errno != 0) {
PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
PyExc_ValueError);
return NULL;
}
Py_INCREF(o);
return o;
}