Inconsistent result from calculation

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)


void setup()
{
    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);                               

}

Hello @RMurphy195,

Take a look here in the Troubleshooting section and you will find the answer:

https://github.com/processing/processing/wiki

This is the topic:
Why does 2 / 5 = 0 instead of 0.4?

:)

2 Likes

In Java, a division of 2 integer operands result in 1 integer value.

Function minute() returns a an int value. 60 itself is an int as well. So result is an int too.

As a workaround, suffix 60 w/ a dot so the division will be a float type instead: minute()/60.

2 Likes

Hi
Welcome to our forum

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.

Phew!

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.

Rookie error here then :grinning:

Addendum: BTW the workaround did the job, thanks

2 Likes

This is about Java behavior:
When both operands are 1 of the integer types, the result is truncated as an int.

Nothing to do w/ Processing. No temp variable is created!

1 Like

Hello @RMurphy195,

A related example:

:)

Thanks ,I didn’t know this existed - now bookmarked, and copied to a word doc for when I’m offline!

1 Like