simple math question

Felipe Almeida Lessa felipe.lessa at gmail.com
Sat Feb 11 15:07:30 EST 2006


Em Sáb, 2006-02-11 às 14:52 -0500, John Salerno escreveu:
> Hi all. I'm just starting out with Python, so I'm a little slow right 
> now. :)
> 
> Can someone explain to me why the expression 5 / -2 evaluates to -3, 
> especially considering that -2 * -3 evaluates to 6?
> 
> I'm sure it has something to do with the negative number and the current 
> way that the / operator is implemented, but why doesn't it evaluate to 
> -2 instead?

It has to do with floating point operations. If you evaluate 5 / -2.0 or
5.0 / -2 you will have -2.5. It gives you -3 because of rounding to
integers. Look:

>>> round(-2.5)
-3.0
>>> round(+2.5)
3.0

This behavior is because -round(x) should be equal to round(-x).

Cya,
Felipe.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"




More information about the Python-list mailing list