Odd math related issue.

Alexandru Palade alexandru.palade at sellerengine.com
Mon Jul 21 08:21:49 EDT 2008


However, you should be carefully because using an %i modifier for a
what-should-be a float value truncates the value in a way you may not
expect.

What I mean is that if you have sent 2 out of 3 bytes, the math will be
200/3 which with the %i modifier will print 66, rather than 66.6 (or at
least 67 which is closer - have a look at the round() function).

Another thing, you could have just added a dot after the constant in
order to promote the expression to be evaluated as float. As in
    percentage = bytes_transferred / /self/.__sessions[path].total_bytes
* 100.
(notice the last dot)

Fredrik Lundh wrote:
> Robert Rawlins wrote:
>
>> I’ve got what seems to me to be a totally illogical math issue here 
>> which I can’t figure out. Take a look at the following code:
>>
>>         /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, 
>> /self/.__sessions[path].total_bytes))
>>
>>         percentage = bytes_transferred / 
>> /self/.__sessions[path].total_bytes * 100
>>
>>         /self/.__logger.info(/"%i"/ % percentage)
>>
>> Seems fairly straight forward, you would think. It takes two values 
>> and calculates the percentage of one from the other, however, 
>> percentage always comes back as ‘0’ for some reason, look at this log 
>> output.
>
> if you divide two integers, you'll get an integer back (in Python 2.X, 
> at least).  quick fix:
>
>      percentage = bytes_transferred * 100 / total_bytes
>
> </F>
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>




More information about the Python-list mailing list