2

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?

Ribz
  • 551
  • 1
  • 4
  • 13
  • 2
    Possible duplicate of [Floating point inaccuracy examples](https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples) – Kijewski Jul 17 '17 at 14:09
  • 1
    If you want to learn how to estimate the needed epsilon then google "numerical stability floating point math". Alas, its Wikipedia article is terrible. – Kijewski Jul 17 '17 at 14:15

2 Answers2

6

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?

Erik Godard
  • 5,930
  • 6
  • 30
  • 33
3

Floating point arithmetic is not exact, so testing for equality will not always work as would be expected with infinite precision.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101