CMU 15-110: Principles of Computing
The Distance Formula
(and checking if a point is inside a circle)
Here is the reasoning behind this line of code in the Events and Conditionals notes:
d = ((event.x - data.cx)**2 + (event.y - data.cy)**2)**0.5
1. The distance formula
This line of code is using the distance formula. So let's start with being sure we all understand that. First, please watch the first 1:45 of this . So now you know the distance formula (and why it is true):
2. The distance formula in Python
Now, how do we write the distance formula in Python? Well, we need the exponentiation operator, which is ** (two asterisks). So 2**4 is 16, and in general, a**b is "a raised to the b power".
Also, we'll need to take square roots. But a square root is just raising to the one-half or 0.5 power. So 4**0.5 is the square-root of 4, or 2.
Now we can write the distance formula in Python. The distance from (x1, y1) to (x2, y2) is:
d = ((x2 - x1)**2 + (y2 - y1)**2)**0.5
Notice how we have parentheses around the entire expression on the right, and we raise the whole thing to 0.5, so we are taking the square root of that whole thing. Great.
3. Returning to that piece of code...
The code from class, once again, is this:
d = ((event.x - data.cx)**2 + (event.y - data.cy)**2)**0.5
Now, this is just the distance formula, but instead of going from (x1, y1) to (x2, y2), this goes from (event.x, event.y) to (data.cx, data.cy). See?
Now, why are we doing that?
4. Checking if a point is inside a circle
Let's briefly digress and ask how we know if a point is inside a circle. Draw a picture of a circle, and then draw a point A that's just inside of it. Now, draw a line from the circle's center to A. That line is shorter than the circle's radius, right? In fact, for any point A inside a circle, the distance from the circle's center to that point cannot be larger than the circle's radius. That's the key.
So: to check if a point is inside a circle, just confirm that the distance from the point to the circle's center is no larger than the circle's radius. Excellent.
5. Checking if a mouse press is inside a circle in Tkinter
Now let's make this real by checking if a mouse press is inside a circle in Tkinter. We'll represent the circle's center using (data.cx, data.cy). As for the mouse press, that occurs at the point (event.x, event.y).
So, from the previous section, we know the click was in the circle if the distance from the point (event.x, event.y) to the circle's center (data.cx, data.cy) is no greater than the circle's radius.
And that distance can be found using the distance formula, as such:
d = ((event.x - data.cx)**2 + (event.y - data.cy)**2)**0.5
So now we can just confirm that (d <= data.r), that is that the distance is no larger than the circle's radius, and we then know the click was inside the circle.
And that fully explains that line of code.
Hope this helps. :-)