In producing a clock (part of my learning curve) I couldn’t get the offset for the hour hand to work. I did solve the problem. I identified the cause as being a calculation that did not produce the expected result and, having corrected it, I would like to understand why the original didn’t work. A stripped-down section of code is attached that reproduces the problem, if anyone could explain why I get a 0 result from the “incorrect” version that would be appreciated thanks
// Different version of calc gives different result
// Should be the same, shouldn't they?
// (Part of code to produce offset for hour hand on a clock)
float hourInterval = 360/12; //Angle through which hour hand moves per hour
float hourAngle1 = ((minute()/60)*hourInterval); //Original code, gives 0 answer
float hourAngle2 = ((minute()*hourInterval)/60); //Corrected code
println("hourangle1 = " + hourAngle1 + " \nhourangle2 = " + hourAngle2);
Thanks all - I think I understand now whats going on …
Because minute is an integer, dividing it by value 60 will always give a fraction (at least in the ranges 0 -59), which is truncated so you end up with 0.
Doing the multiplication first gives a bigger number which, when divided by 60 is less likely to give a 0.nnn (i.e. zero) result. But does not necessarily give an accurate result.
So this is why doing the multiplication first (appears to) give the correct result. But it perhaps is not necessarily accurate even though the end result is that my sketch works well.
So I guess in the background, Processing creates an intermediate variable which it assumes to be integer because the operands are both integer? And I guess the workaround causes this intermediate field to be a float.