Differences between revisions 1 and 2
Revision 1 as of 2023-04-24 19:35:28
Size: 1359
Comment:
Revision 2 as of 2023-06-15 18:35:31
Size: 1445
Comment:
Deletions are marked like this. Additions are marked like this.
Line 59: Line 59:
[[https://pymotw.com/3/fractions/|Python Module of the Day article for fractions]]

Python Fractions

fractions is a module supporting arithmetic with rational numbers.


Usage

Fraction

A Fraction can be instantiated from integers, floats, strings, and Decimal objects.

import fractions

fractions.Fraction(-8, 5)    #Fraction(-8, 5)

# The numerator-denominator pair can be given as separate arguments or as a formatted string
fractions.Fraction('-8/5')   #Fraction(-8, 5)

# Fraction reduces and moves signs to the numerator automatically
fractions.Fraction(16, -10)  #Fraction(-8, 5)

# Note the defaults
fractions.Fraction(123)      #Fraction(123, 1)
fractions.Fraction()         #Fraction(0, 1)

The components can be access with the numerator and denominator properties, or the as_integer_ratio method.


Limit_Denominator

To approximate a fraction, use the limit_denominator method. It takes an integer argument that is used to construct a new Fraction with a denominator no larger than that integer.

import fractions

fractions.Fraction('3.1415926535897932').limit_denominator(1000)  #Fraction(355, 113)


See also

Python fractions module documentation

Python Module of the Day article for fractions


CategoryRicottone

Python/Fractions (last edited 2023-06-15 18:35:31 by DominicRicottone)