0

Make a function in_circle(x, origin) that uses distance to determine if a two-dimensional point falls within the unit circle with a given origin. [Related question ][1]

def distance(x, y):
    return math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)

How can I use distance (x,y) function inside the following function

def in_circle(x, origin = [0]*2):

to determine if a point falls within the circle. [1]: Detect if user clicks inside a circle

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
esilik
  • 2,303
  • 3
  • 16
  • 24
  • You need to define the circle you are working with, first. You need to know the radius of the circle, then calculate the distance between your point of interest and the origin of the circle, and finally compare the magnitude of that distance with the radius. If the radius is greater than the calculated distance, then the point is in the circle. Otherwise, it is outside the circle. – Abdou Jan 07 '17 at 17:22
  • Since it is a unit circle it's radius is 1 and d<1 case return True for looked point. I know about the algorithm but I have stuck with the function in there (This is an exercise from Data Camp, I have to use that defined in_circle function). How can I relate the distance function with in_circle function or with its parameters? @Abdou – esilik Jan 07 '17 at 17:33

2 Answers2

1

i assume you define the radius

#example for 5 radius
r = 5
def in_circle(x, origin = [0]*2):
    if distance(x,origin)<r:
        print("inside")
    else:
        print("outside")
0

The first thing you need to do here is define how a circle is structured. For this example, I am defining a circle as a tuple of two elements, where the first element is coordinates of the origin point and the second element is the radius of the circle. For instance, ((0,0), 3) is a circle with origin (0,0) and a radius of 3.

Now that you have defined a circle, you can move forward with checking a given point is inside a circle as follows:

import math

# Create a unit circle
mycircle = ((0,0), 1)

# Create points
mypoint1 = (3,3)
mypoint2 = (1,1)


# Your definition of distance function
def distance(point1, point2):
    return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)

# Defining the function to check if the point is inside or on a circle
def in_circle(point, circle):
    origin, radius = circle
    return radius >= distance(point, origin)

# Test
print(in_circle(mypoint1, mycircle))
# False

print(in_circle(mypoint2, mycircle))
# False

I hope this helps.

Abdou
  • 12,931
  • 4
  • 39
  • 42