Koen - 4 months ago 33

Python Question

There is something extremely strange happening if I do som 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):

the only difference between both multiplication 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 completely no idea how this is even possible

Answer

Parenthesis change the order of evaluation, and the expression inside them is evaluated first. Here, since 60 and 368 are both integer literals they are divided using integer division - meaning only the "whole" part is kept. Since 60 is smaller than 368 their integer division is 0. From there on, the result is obvious - you've got a series of multiplications and divisions where one of multipliers is 0, so the end result would also be 0.

To prevent this you could express the numbers as floating point literals - 60.0 and 368.0. (Well, technically, just using 60.0 would be sufficient here, but for consistency's sake I recommend representing all the numbers as floating point literals).