Ribz Ribz - 7 months ago 26
Python Question

Test if a random point belongs to a circumference of a circle using Python

I am trying to generate a random point on the circumference of a circle using Python.

I have a circle of centre (0, 0) and of radius 50. I did the following.

import numpy as np
angle = 2 * np.pi * np.random.rand()
x = np.cos(angle) * 50
y = np.sin(angle) * 50

But when I test to see if the point is actually on the circle circumference, I did this

x ** 2 + y ** 2 == 50 ** 2

but I get


Why is this?

Answer Source

This is the result of floating point imprecision. In general, it is a bad idea to compare two floats for equality, and you should instead test to see if they are within a certain amount of each other. For example,

epsilon = 0.000001
print abs(x ** 2 + y ** 2  - 50 ** 2) <= epsilson

See also: How should I do floating point comparison?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download