Search code examples
pythondivisionmultiplication

multiplication gives zero if I put elements into brackets (python)


There is something extremely strange happening if I do some ordinary calculations in Python. If I do a multiplication whithout brackets, it gives the right thing, but if set some things into brackets the total multiplication becomes equal to zero.

For those who don't believe (I know that it sounds strange):

>>> print( 1.1*1.15*0.8*171*15625*24*(60/368*0.75)/1000000 )
0.0
>>> print( 1.1*1.15*0.8*171*15625*24*60/368*0.75/1000000 )
7.93546875

as shown in this Jupyter screenshot.

The only difference between both multiplications is that in the first there are brackets around 60/368*0.75.

How is this possible and what can I do against it? I have no idea how this is even possible.


Solution

  • If you divide integers a,b in python the result is the floor of the division, thus if a < b we get: floor(a,b)=0

    With brackets you have the operation 60/368 which gives 0.

    But without brackets the number 60 is first multiplied by everything before it, which results in some double value so dividing this value by 368 does not yield 0.