2017-07-17 69 views
2

我想在使用Python的圓的圓周上生成一個隨機點。使用Python測試一個隨機點是否屬於一個圓的圓周

我有一箇中心(0,0)和半徑爲50的圓。我做了以下操作。

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

但是當我測試一下,看看如果該點實際上是對圈圍,我這樣做

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

,但我得到

False 

這是爲什麼?

+2

的[浮點不精確的例子]可能的複製(https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples) – kay

+1

如果您想學習如何估算所需的epsilon,然後谷歌「數值穩定浮點數學」。唉,它的維基百科文章是可怕的。 – kay

回答

6

這是浮點不精確的結果。一般來說,比較兩個花車的平等性是一個不好的主意,你應該測試一下,看看它們是否在一定的範圍內。例如,

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

參見:How should I do floating point comparison?

3

浮點算術並不精確,因此測試相等性不會像預期的那樣具有無限精度。

相關問題