More random python observations from a perl programmer

Tom Christiansen tchrist at mox.perl.com
Thu Aug 19 12:40:56 EDT 1999


     [courtesy cc of this posting mailed to cited author]

>I had a look at this again. Despite the fact that the text in
>the above example is a bit misleading by "int of" where
>a round() takes place, which version of Python/architecture
>did you use? I get the expected result, see below.

Both SunOS and Linux round every other 5s up and down.  Somebody important
(IEEE I think) says you have to do this in order to regularize round-off
error.  Perl, Python, and C all behave identically on this on both those
platforms.  (I tested Perl and C on BSD, too, and they're the same.)
It's only Python's round() function that doesn't follow this.

1. C code 

    main() {
	printf("Float %g rounds to %.0f\n", 1.5, 1.5);
	printf("Float %g rounds to %.0f\n", 2.5, 2.5);
	printf("Float %g rounds to %.0f\n", 3.5, 3.5);
	printf("Float %g rounds to %.0f\n", 4.5, 4.5);
    }

    OUTPUT:

	Float 1.5 rounds to 2
	Float 2.5 rounds to 2
	Float 3.5 rounds to 4
	Float 4.5 rounds to 4

2. Perl code

    main() {
	printf("Float %g rounds to %.0f\n", 1.5, 1.5);
	printf("Float %g rounds to %.0f\n", 2.5, 2.5);
	printf("Float %g rounds to %.0f\n", 3.5, 3.5);
	printf("Float %g rounds to %.0f\n", 4.5, 4.5);
    }
    main();  # not called by default

    OUTPUT:

	Float 1.5 rounds to 2
	Float 2.5 rounds to 2
	Float 3.5 rounds to 4
	Float 4.5 rounds to 4

3. Python code: (did it really have to look so different? :-)

    # remember to un-indent this or it won't run
    print "Float %g rounds to %.0f" % (1.5, 1.5);
    print "Float %g rounds to %.0f" % (2.5, 2.5);
    print "Float %g rounds to %.0f" % (3.5, 3.5);
    print "Float %g rounds to %.0f" % (4.5, 4.5);

    OUTPUT:

	Float 1.5 rounds to 2
	Float 2.5 rounds to 2
	Float 3.5 rounds to 4
	Float 4.5 rounds to 4

You can see this in other situations, like working with pennies.
Imagine If you have extra half-pennies, like one and half cents,
two and half, there and half, etc:

    >>> print "You have $%0.2f bucks" % (2.5/100)
    You have $0.03 bucks
    >>> print "You have $%0.2f bucks" % (3.5/100)
    You have $0.04 bucks
    >>> print "You have $%0.2f bucks" % (4.5/100)
    You have $0.04 bucks

Strange but true.  It's supposed to even out the error.
Ask a numbers guy.  I'm just the messenger. :-)

As for the tuple thing, why can I say

    print "You have $%0.2f bucks" % (4.5/100)

How is that a singleton tuple?  Don't I have to use
a trailing comma?  It won't let me!  Why is 

    print "You have $%0.2f bucks" % (4.5/100,)

illegal, but 

    print "You have $%0.2f bucks" % ((4.5/100,) * 2)

mandatory?  Was this (elt,) thing just an, er, unforeseen design
misfeature? Yes, I tripped me up again. :-(

--tom
-- 
I have a different view of the world.  --Andrew Hume. Show&Tell '87




More information about the Python-list mailing list