0
votes

I've been having problems updating the position of my mouse after performing an operation on the variable I assign mouseX and mouseY to.

def setup():
    size(500,500)

def draw():
    background(255,255,255)
    noStroke()
    fill (0,0,0)
    a1 = mouseX
    b1 = mouseY

    print a1
    a1 = a1*(4/500) - 2 #trans to [-2,2]
    b1 = b1*(4/500) - 2
    print a1

when I print a1, the first value I print in updated but the second value is not. So if I move my mouse position to (250,250) I get 250 as the first output and -2 as my second value. I am not too familiar with python as I never truly learned it and I've looking up ways but couldn't find one. Please help. Thank you

1
In Python 2.x, 4/500 equals zero - since it's being performed as an integer operation. Convert at least one of the operands to a float to get float division - 4 / 500.0 perhaps.jasonharper
use the float type in the expression: for instance, float(4)/500JeanClaudeDaudin

1 Answers

0
votes

I don't know anything about Python, but in regular Processing (which is basically just Java), int values cannot hold decimal places. If you try to store a decimal place in an int value, it will truncate by just chopping off the decimal part.

Here are some examples:

int x = 3 / 2; // 1.5 is truncated so x is just 1
int y = 1 / 2; // 0.5 is truncated so y is just 0

Now, let's split your code into multiple steps. It might look like this:

int multiplier = 4 / 500;
a1 = a1 * multiplier;
a1 = a1 - 2;

Hopefully you can see that 4 / 500 is truncated so it's just 0. Then when you multiply it by a, you get 0. Then you subtract 2, so the end result is -2.

You should get into the habit of splitting your code up into multiple steps like this so it's easier for you to debug your code.

Now, to fix this problem, you need to use a float variable, which does allow for decimal places. Since you're using literals (4 and 500 are both literals), you could do something like this:

 a1 = a1 * (4.0 / 500.0) - 2

Now this code use 4.0 and 500.0, so the result is 0.008 with the decimal part included. Then the rest of your calculations will work how you expected them to.

Depending on how Processing types work, you might also be able to do this:

a1 = a1 * 4 / 500 - 2

If a1 is already a float value, then this will work because a1 * 4 is calculated first, and the result is a float, and the rest of it should work how you expect. But that will only work if a1 is already a float.

You should also try googling "python int division" for a ton of results.