converting a float to decimal type in Python
Question: I have an array that grows with each iteration of a loop:

    
    
    for i in range(100):
        frac[i] = some fraction between 0 and 1 with many decimal places
    

This all works fine. When I check the **type(frac[i])** , I am told that it is
**'numpy.float64'**.

For my code to be as precise as I need it to be, I need to use the decimal
module and change each **frac[i]** to the decimal type.

I updated my code:

    
    
    for i in range(100):
        frac[i] = some fraction between 0 and 1 with many decimal places
    
        frac[i] = decimal.Decimal(frac[i])
    

But when I check the type, I am STILL told that **frac[i]** is
**'numpy.float64'**.

I have managed to change other variables to decimal in this way before, so I
wonder if you could tell me why this doesn't seem to work.

Thank you.


Answer: Depending where your fractions are coming from, you may find it ideal to use
the [fractions](http://docs.python.org/2/library/fractions.html) module. Some
examples from the docs:

    
    
    >>> from fractions import Fraction
    >>> Fraction(16, -10)
    Fraction(-8, 5)
    >>> Fraction(123)
    Fraction(123, 1)
    >>> Fraction()
    Fraction(0, 1)
    >>> Fraction('3/7')
    Fraction(3, 7)
    >>> Fraction(' -3/7 ')
    Fraction(-3, 7)
    >>> Fraction('1.414213 \t\n')
    Fraction(1414213, 1000000)
    >>> Fraction('-.125')
    Fraction(-1, 8)
    >>> Fraction('7e-6')
    Fraction(7, 1000000)
    >>> Fraction(2.25)
    Fraction(9, 4)
    >>> Fraction(1.1)
    Fraction(2476979795053773, 2251799813685248)
    >>> from decimal import Decimal
    >>> Fraction(Decimal('1.1'))
    Fraction(11, 10)
    

You can also perform all of the regular arithmetic operations; if the result
can't be expressed as a fraction, it will be converted to a float:

    
    
    >>> Fraction(3, 4) + Fraction(1, 16)
    Fraction(13, 16)
    >>> Fraction(3, 4) * Fraction(1, 16)
    Fraction(3, 64)
    >>> Fraction(3, 4) ** Fraction(1, 16)
    0.982180548555
    

