I took a quick look at the fractions package that handles Python built-in fractions.

Now that I've learned about the existence of the Python built-in fractions package that handles fractions, let's take a quick look at how it behaves.

Environment used in the article

Use Python 3.8.6. For the rest, we'll just use the built-in fractions package.

Basic usage

First of all, you need to import the fractions package to handle it. In particular, the Fraction class is the main usage, so import that.

from fractions import Fraction

The Fraction class accepts a first argument, the numerator, and a second argument, the denominator.

f = Fraction(numerator=3, denominator=4)

If you try to display an instance of the Fraction class on an interactive shell or Jupyter, it will be displayed as a repr, including the values ​​of the numerator and denominator.

>>> f

Fraction(3, 4)

If you look through the print function, it will be displayed as 3/4.

>>> print(f)

3/4

Can be compared with int and float

It seems that Fraction instances can be compared with ints and floats as they are.

Comparison with int


>>> f = Fraction(numerator=4, denominator=4)
>>> f == 1

True

Comparison with float


>>> f = Fraction(numerator=3, denominator=4)
>>> f == 3 / 4

True

If it is an int value, Fraction is returned even if four arithmetic operations are performed.

If you perform four arithmetic operations on a Fraction instance with int etc., the Fraction instance will be returned as it is.

>>> Fraction(3, 4) + 1

Fraction(7, 4)
>>> Fraction(5, 4) - 1

Fraction(1, 4)
>>> Fraction(3, 4) * 2

Fraction(3, 2)

Fraction also returns four arithmetic operations between Fractions

If you add Fractions together, the result will also be an instance of Fractions.

>>> Fraction(1, 4) + Fraction(1, 4)

Fraction(1, 2)

Fraction + Fraction + int will return Fraction as it is.

>>> Fraction(1, 4) + Fraction(1, 4) + 1

Fraction(3, 2)

Float is returned when four arithmetic operations are performed with the value of float.

If you perform four arithmetic operations with the values ​​of Fraction and float, the result will be float.

>>> Fraction(3, 4) + 1.5

2.25

The denominator argument can be omitted

By specifying float as the argument of the numerator (numerator) of the first argument, you can create a Fraction instance even if you omit the denominator argument of the denominator.

>>> Fraction(numerator=0.25)

Fraction(1, 4)
>>> Fraction(numerator=0.26)

Fraction(1170935903116329, 4503599627370496)
>>> 1170935903116329 / 4503599627370496

0.26

You can also specify a string in the numerator argument

You can also specify a character string using a half-width slash, such as 1/4, in the numerator argument.

>>> Fraction(numerator='1/4')

Fraction(1, 4)

Automatically reduced

If you can reduce the amount when you create an instance of Fraction or perform a calculation, the reduction will be executed automatically.

>>> Fraction(2, 4)

Fraction(1, 2)
>>> Fraction(1, 6) + Fraction(1, 6)

Fraction(1, 3)

You can get the approximate value of an irrational number with the limit_denominator method

If you specify an irrational number, you can specify the maximum denominator value (max_denominator argument) to get an approximate value within the range of that value or less.

>>> Fraction(3.14159265359)

Fraction(3537118876014453, 1125899906842624)

Setting the denominator is limited to 10 or less


>>> Fraction(3.14159265359).limit_denominator(max_denominator=10)
Fraction(22, 7)

>>> 22 / 7
3.142857142857143

Setting the denominator is limited to 150 or less


>>> Fraction(3.14159265359).limit_denominator(max_denominator=150)
Fraction(3.14159265359).limit_denominator(max_denominator=150)

>>> 355 / 113
3.1415929203539825

References / Reference Sites

Recommended Posts

I took a quick look at the fractions package that handles Python built-in fractions.
Take a look at the Python built-in exception tree structure
I took a closer look at why Python self is needed
Take a look at the built-in exception tree structure in Python 3.8.2
A memo that I touched the Datastore with python
I took a look at the contents of sklearn (scikit-learn) (1) ~ What about the implementation of CountVectorizer? ~
A quick look at your profile within the django app
I tried running the Python Package Repository (Warehouse) that supports PyPI
A story that struggled to handle the Python package of PocketSphinx
[Emacs] I had a problem installing the Python auto-completion package jedi (mac)
[Python] A program that rounds the score
The story of IPv6 address that I want to keep at a minimum
Around the authentication of PyDrive2, a package that operates Google Drive with Python
Let's look at a differential equation that cannot be solved normally in Python
A memo that I wrote a quicksort in Python
A story that was convenient when I tried using the python ip address module
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
I learned Python with a beautiful girl at Paiza # 02
[Python] A program that counts the number of valleys
I learned Python with a beautiful girl at Paiza # 01
I made a VM that runs OpenCV for Python
Created a Python library DateTimeRange that handles time ranges
A story that I was addicted to at np.where
I felt that I ported the Python code to C ++ 98.
Tasks at the start of a new python project
Take a closer look at the Kaggle / Titanic tutorial
[Python] A program that compares the positions of kangaroos.
I wrote a Python script that exports all my posts using the Qiita API v2
Let's take a quick look at CornerNet, an object detector that does not use anchors.
A Python script that goes from Google search to saving the Search results page at once
I replaced the Windows PowerShell cookbook with a python script.
Try using the Python web framework Django (2) --Look at setting.py
I just changed the sample source of Python a little.
I made a package to filter time series with python
python Condition extraction from a list that I often forget
I made a quick feed reader using feedparser in Python
Creating a Python script that supports the e-Stat API (ver.2)
I tried "a program that removes duplicate statements in Python"
Miscellaneous notes that I tried using python for the matter
[Python] A program that finds the most common bird types
A Python script that compares the contents of two directories
I wrote a script that splits the image in two
Hannari Python At the LT meeting in December, I made a presentation on "Python and Bayesian statistics".
[Python] I tried to make a simple program that works on the command line using argparse.
A story that didn't work when I tried to log in with the Python requests module