Elementary string-formatting

John Machin sjmachin at lexicon.net
Sun Jan 13 00:46:22 EST 2008


On Jan 13, 3:15 pm, Odysseus <odysseus1479... at yahoo-dot.ca> wrote:
[snip]
>
> P.S. Is there a preferable technique for forcing floating-point division
> of two integers to that used above, multiplying by "100.0" first? What
> about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n /
> m"?

> Odysseus

You obviously haven't tried float(n / m), or you wouldn't be asking.
Go ahead and try it.

"Preferable" depends on whether you want legibility or speed.

Most legible and slowest first:
1. float(n) / float(m)
2. n / float(m)
3. 1.0 * n / m
# Rationale so far: function calls are slow
4. If you have a lot of this to do, and you really care about the
speed and m (the denominator) is constant throughout, do fm = float(m)
once, and then in your loop do n / fm for each n -- and make sure you
run properly constructed benchmarks ...

Recommendation: go with (2) until you find you've got a program with
a real speed problem (and then it probably won't be caused by this
choice).

HTH,
John



More information about the Python-list mailing list