Representing fractions (was: Help me with this code)

Ben Finney ben+python at benfinney.id.au
Tue Nov 5 21:06:41 EST 2013


chovdary at gmail.com writes:

> def sequence_b(N):
>     N = 10
>     result = 0
>     for k in xrange (1,N):
>         result  +=  ((-1) ** (k+1))/2*k-1

Every number here is an integer. Python 2 will keep all the computations
integers by default::

    $ python2
    >>> 1 / 2
    0

You want to use Python 3, which does “true division” by default::

    $ python3
    >>> 1 / 2
    0.5

> But i want output as
> 1
> -1/3
> 1/5
> -1/7
> 1/9
> -1/11
> 1/13
> -1/15
> 1/17
> -1/19

You're not going to get that output from Python built-in number types.

If you want numbers which represent fractions (as opposed to integers,
or decimal numbers, or floating-point numbers), you want the ‘fractions’
module <URL:http://docs.python.org/3/library/fractions.html> which will
represent the number explicitly with numerator and denominator::

    $ python3
    >>> import fractions
    >>> result = fractions.Fraction(1) / fractions.Fraction(2)
    >>> result
    Fraction(1, 2)
    >>> print(result)
    1/2

-- 
 \          “A hundred times every day I remind myself that […] I must |
  `\       exert myself in order to give in the same measure as I have |
_o__)                received and am still receiving” —Albert Einstein |
Ben Finney




More information about the Python-list mailing list