[PYTHON] Is the number equivalent to an integer?

Introduction

Numerical values such as 1.23 and 34.5 are decimal numbers, aren't they? It is not an integer. 1.0 and 34.0 are also decimal numbers, but they may be called integers.

Fractions such as 1/3 are also not integers. A 3/3 fraction can be called an integer.

Here we define an integer like this. "In addition to 1 and 34, numbers with 0 decimal places such as 1.0 and 3.0 and fractions with the same numerator and denominator"

In this article, we'll look at how to determine literals that are fractions and decimals but also integers.

In the first place, what is the expression method of fractions?

For pure integers and decimals, all you have to do is enter a number in the variable, like this:


a = 123
b = 123.4
print(a)
print(b)

# 123
# 123.4

On the other hand, when it comes to fractions, if you write "1/4" as above, the calculation process will be performed automatically, so it cannot be expressed. So we use Python's standard library fractions.

from fractions import Fraction

f = Fraction(1, 3)
print(f)

# 1/3

Easy to distinguish decimal numbers

Try to determine decimals using the is_integer () method

Decimal numbers can be determined by using the is_integer () method.

n = 1.23
print(n.is_integer())
# False

m = 1.00
print(m.is_integer())
# True

Try to determine the fraction using the is_integer () method

However, it cannot be used for fractional representation using fractions.


from fractions import Fraction

f = Fraction(1, 3)
print(f.is_integer())

# AttributeError: 'Fraction' object has no attribute 'is_integer'

Convert fractions to decimals and apply is_integer ()

What if I can't use the is_integer () method for fractions? If you convert the literal defined as a fraction to a decimal (float type), the is_integer () method should work fine.

A literal defined as a fraction is converted to a decimal by dividing it by ~~ 1.0. ~~ Please point out in the comment section I changed it to be intuitive and easy to understand by the approach of float (hoge).

By inserting this operation, it is possible to judge by the is_integer () method.

from fractions import Fraction

f = Fraction(1, 3)
g = float(f)

x = Fraction(3, 3)
y = float(x)

print(g)
print(y)
# 0.3333333333333333
# 1.0

print(g.is_integer())
print(y.is_integer())
# False
# True

Bonus: What if you don't have the is_integer () method?

I will also introduce a detour judgment method that I thought at the time when I did not know the existence of is_integer.

** If the number rounded up to the nearest whole number and the number rounded down to the nearest whole number match, it is judged as an integer ** We will approach based on the idea.

For example, for the number 1.1, rounding up to the nearest whole number gives 2. Conversely, it is 1 if it is rounded down to the nearest whole number. This is not an integer because the numbers do not match.

If it is 1.0, it will be the same 1 regardless of whether it is rounded up or down after the decimal point, so if this is an integer, that is the reason.

To round up the decimal point, use the ceil () method of the math library, By using the floor () method of the math library for devaluation, it is possible to make such a determination. The function below is also valid for decimal numbers such as 1.23.

from fractions import Fraction
import math


def isInteger(n):

    nx = math.ceil(n)
    ny = math.floor(n)

    return (nx == ny)


n = Fraction(1, 3)
m = Fraction(3, 3)

print(isInteger(n))
print(isInteger(m))
# False
# True

Recommended Posts

Is the number equivalent to an integer?
[Question] In sk-learn random forest regression, an error occurs when the number of parallels is set to -1.
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
[Introduction to AWS] The first Lambda is Transcribe ♪
An introduction to data analysis using Python-To increase the number of video views-
How to identify the system call number ausyscall
An article summarizing the pitfalls addicted to python
[Ruby on Rails] From application creation to server startup & what is the port number?
[Curse of dimensionality] If the number of sensors is changed to ∞, can anomaly be detected?
Check if the string is a number in python
python beginners tried to predict the number of criminals
How to create an article from the command line
How to know the port number of the xinetd service
How to get the number of digits in Python
Save the graph drawn by pyqtgraph to an image
Determine if an attribute is defined in the object
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
python (2) requires self because the method is an instance method
[Python] Why the referenced objects have the same ID when the same integer is assigned to different variables
[For beginners] I want to explain the number of learning times in an easy-to-understand manner.
How to specify an infinite number of tolerances in the numeric argument validation check of argparse
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
The road to Pythonista
The road to Djangoist
What is an iterator?
I want to initialize if the value is empty (python)
How to find the optimal number of clusters in k-means
Solve number sorting (equivalent to paiza rank D) in Python
[python] Change the image file name to a serial number
How to manipulate the DOM in an iframe with Selenium
If an engineer is asked to entertain a wedding reception
Try to improve the accuracy of Twitter like number estimation
Code to send an email based on the Excel email list
How to increase the number of machine learning dataset images
Let's create an external specification that is easy to handle
An introduction to the modern socket API to learn in C
I want to map the EDINET code and securities number
Change the installation destination when --user is added to pip
The story that the private key is set to 600 with chmod
Is there a secret to the frequency of pi numbers?