[Tutor] Integer division (Was: Re: Format strings for variables - how?)

Kalle Svensson kalle@gnupung.net
Thu, 8 Feb 2001 09:11:29 +0100


--wac7ysb48OaltWcw
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Sez David Porter:
> * Viktor Lakics <lakicsv@usa.net>:
> > a=3D1
> > b=3D3
> > print "%0.2f" %(a/b)
> >=20
> > The above code gives me 0.00 as a result, while I wanted to get
> > 0.33...
>=20
> The reason is that the numbers you are dividing are not floats. Because of
> that, you are doing integer division.
>=20
> >>> a =3D 1.0
> >>> b =3D 3
> print "%0.2f" %(a/b)
>=20
> gives 0.33. You must add a decimal point to one (or more) of the numbers.

Now, you might (should, I think) wonder:  Why?
Basically, I think there are two reasons python has integer division.

 1) C has truncating integer division.  Python is implemented in C.  Some of
the initial target users for Python were C programmers.

 2) There is no way to handle division of two integers that everybody likes.
Some want truncating integer division (chopping off the remainder), some wa=
nt
conversion to float (which loses exact representation), some want rational
math (resource intensive), some want the Spanish Inquisition...

 3) It would break a lot of existing code if it was changed tomorrow.
=20
Three reasons.

The way it works today is perhaps not the most obvious for a newcomer to
programming or one with experience in languages using different solutions,
but when you get used to it, it's at least as good as any of the
alternatives, IMHO.

HTH,
  Kalle
--=20
Email: kalle@gnupung.net     | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD

--wac7ysb48OaltWcw
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE6glSxdNeA1787sd0RAtwIAKCm23fTcd0RfspzKeirl1DU2n5nngCgtA0J
ohI2o2GolV00BvYPjBEuKW8=
=v/gD
-----END PGP SIGNATURE-----

--wac7ysb48OaltWcw--