[Tutor] small program in Python and in C++

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 2 Jul 2002 15:04:49 -0700 (PDT)


On Tue, 2 Jul 2002, Rob wrote:

> I thought I'd pass it all along to the Tutor list in case it makes a
> good example for anyone (or if anyone cared to point out other ways to
> do it, etc.). If you know a little C++ and are looking into Python, or
> vice versa, you might like it on some level.
>
>
> # calculate body mass index
> bodyMassIndex = 703 * ( weight / ( height * height ) )

It might be good to make this a function --- even though it's so simple,
having it as a function makes it easy to reuse this calculation if we ever
need it later.  As an additional bonus, if we write it as a function, we
can play with it very easily within the interactive interpreter:


###
>>> def bodyMassIndex(weight, height):
...     return 703 * ( weight / ( height * height ) )
...
>>> bodyMassIndex(175, 6.5)
2911.834319526627
>>> bodyMassIndex(175, 6)
2812
###


Oh!  It also reveals that we need to be careful about the types that we
use to do the calculation when division comes into play.


C++'s variable typing forces weight and height to be floats, but we don't
restrict the same in Python. If "from __future__ import true_division"
isn't on, we should probably force floating point division:

###
>>> def bodyMassIndex(weight, height):
...     return 703 * ( weight / float( height * height ) )
...
>>> bodyMassIndex(175, 6)
3417.3611111111109
###


Hope this helps!