off topic but please forgive me me and answer
Tim Chase
python.list at tim.thechases.com
Thu Apr 1 23:34:46 EDT 2010
Steven D'Aprano wrote:
>> That's because you need to promote one of them to a float so you get a
>> floating-point result:
>>
>> >>> 1/2 * 1/2
>> 0
>> >>> 1/2 * 1/2.0
>> 0.0
>>
>> Oh...wait ;-)
>
> Tim, I'm sure you know the answer to this, but for the benefit of the
> Original Poster, the problem is that you need to promote *both* divisions
> to floating point. Otherwise one of them will give int 0, which gives 0.0
> when multiplied by 0.5.
>
>>>> 1.0/2 * 1/2.0
> 0.25
You can get away with just promoting one of them...you just have
to promote the _correct_ one (one involved in the first division)
so that its promotion-of-subresult-to-float carries into all
subsequent operations/operators:
>>> 1/2 * 1/2 # (((1/2)*1)/2)==(((0)*1)/2) in 2.x
0
>>> 1/2 * 1/2.0 # (((1/2)*1)/2.0)==(((0)*1)/2.0) in 2.x
0.0
>>> 1/2 * 1.0/2 # (((1/2)*1.0)/2)==(((0)*1.0)/2) in 2.x
0.0
>>> 1/2.0 * 1/2 # (((1/2.0)*1)/2)
0.25
>>> 1.0/2 * 1/2 # (((1.0/2)*1)/2)
0.25
I'd rather be explicit in *real* code that I'd write and
explicitly float'ify constants or float() integer variables. The
OP's question was both OT and pretty basic middle-school math
that google would have nicely answered[1] so IMHO warranted a bit
of fun. :)
-tkc
[1]
http://www.google.com/search?q=1%2F2+*+1%2F2
More information about the Python-list
mailing list