Ribz - 4 months ago 17

Python Question

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

`False`

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
```