Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #58544

Representing fractions (was: Help me with this code)

From Ben Finney <ben+python@benfinney.id.au>
Subject Representing fractions (was: Help me with this code)
Date 2013-11-06 13:06 +1100
References <612c0028-ae66-4200-b9a5-a613eca94762@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2071.1383703613.18130.python-list@python.org> (permalink)

Show all headers | View raw


chovdary@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Help me with this code chovdary@gmail.com - 2013-11-05 17:51 -0800
  Representing fractions (was: Help me with this code) Ben Finney <ben+python@benfinney.id.au> - 2013-11-06 13:06 +1100
  Re: Help me with this code MRAB <python@mrabarnett.plus.com> - 2013-11-06 02:37 +0000
  Re: Help me with this code Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-06 02:42 +0000
  Re: Help me with this code Dave Angel <davea@davea.name> - 2013-11-05 23:44 -0600
  Re: Help me with this code Piet van Oostrum <piet@vanoostrum.org> - 2013-11-07 09:08 -0400

csiph-web