Decimal and Fraction Numbers in Python

Decimal and Fraction Numbers in Python

We should remember not only integers and floats but also other numeric types: decimal numbers (fixed-precision floating-point numbers) and fraction numbers (rational numbers with both a numerator and a denominator). We can use them in the situation where integers and floats aren’t too good.

When we deal with numerals in a standard way:

>>> 1/4
0.25
>>> 4/7
0.5714285714285714
>>> 6/5
1.2

But we want more.

Fractions
>>> import fractions
>>> dir(fractions)
[‘Decimal’, ‘Fraction’, ‘_PyHASH_INF’, ‘_PyHASH_MODULUS’, ‘_RATIONAL_FORMAT’, ‘_
_all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing__’
, ‘__loader__’, ‘__name__’, ‘__package__’, ‘gcd’, ‘math’, ‘numbers’, ‘operator’,
 ‘re’, ‘sys’]
>>>

Let’s try use it:

>>> s = fractions.Fraction(1,2)
>>> s
Fraction(1, 2)
>>> s + 4
Fraction(9, 2)
>>> s – 2
Fraction(-3, 2)
>>> t = fractions.Fraction(3,2)
>>> t
Fraction(3, 2)
>>> t * 2
Fraction(3, 1)
>>> t / 7
Fraction(3, 14)
>>> u = s + t
>>> u
Fraction(2, 1)
>>> u + fractions.Fraction(1, 6)
Fraction(13, 6)
>>> fractions.Fraction(1,2) +  fractions.Fraction(1,2)
Fraction(1, 1)
>>>

Decimals
>>> import decimal
>>> dir(decimal)
[‘BasicContext’, ‘Clamped’, ‘Context’, ‘ConversionSyntax’, ‘Decimal’, ‘DecimalEx
ception’, ‘DecimalTuple’, ‘DefaultContext’, ‘DivisionByZero’, ‘DivisionImpossibl
e’, ‘DivisionUndefined’, ‘ExtendedContext’, ‘FloatOperation’, ‘HAVE_THREADS’, ‘I
nexact’, ‘InvalidContext’, ‘InvalidOperation’, ‘MAX_EMAX’, ‘MAX_PREC’, ‘MIN_EMIN
‘, ‘MIN_ETINY’, ‘Overflow’, ‘ROUND_05UP’, ‘ROUND_CEILING’, ‘ROUND_DOWN’, ‘ROUND_
FLOOR’, ‘ROUND_HALF_DOWN’, ‘ROUND_HALF_EVEN’, ‘ROUND_HALF_UP’, ‘ROUND_UP’, ‘Roun
ded’, ‘Subnormal’, ‘Underflow’, ‘__doc__’, ‘__file__’, ‘__initializing__’, ‘__lo
ader__’, ‘__name__’, ‘__package__’, ‘__version__’, ‘getcontext’, ‘localcontext’,
 ‘setcontext’]
>>>

Let’s try use it:

>>> l = decimal.Decimal(234.45)
>>> l
Decimal(‘234.44999999999998863131622783839702606201171875’)
>>> l + 345
Decimal(‘579.4499999999999886313162278’)
>>> l – 34
Decimal(‘200.4499999999999886313162278’)

We should use ‘ or “:

>>> l = decimal.Decimal(‘234.45’)
>>> l
Decimal(‘234.45’)
>>>

Let’s see some operations:
>>> k = decimal.Decimal(“2.00”)
>>> k
Decimal(‘2.00’)
>>> n = decimal.Decimal(“24.00”)
>>> n
Decimal(‘24.00’)
>>> n / k
Decimal(’12’)
>>>

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s