0

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

Cats
  • 3
  • 2
  • That's impossible to tell without seeing the .is_integer() method. Unless the question is how such a method could work? – Allaboard Jul 06 '22 at 19:05
  • *How does returing num.is-integer work to determine if the number has a .0 if the number is a float?* -- you need to read the source code of `float.is_integer()` – user47 Jul 06 '22 at 19:06
  • If you want to know how the .is_integer() method could work in principle then see [this question](https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point) – Allaboard Jul 06 '22 at 19:13
  • You aren't returning `num.is_integer`; you are calling it and returning the value *it* returns. `is_integer` basically just *defers* to `float.is_integer` to make the decision. – chepner Jul 06 '22 at 19:25

1 Answers1

1

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;
}
Bob th
  • 276
  • 1
  • 6