2017-02-20 98 views
0

假设我正在考虑M=N**2其中N是一个整数。看来numpy.sqrt(M)返回一个浮点数(实际上是numpy.float64)。安全采取`int(numpy.sqrt(N))`

我能想象,有可能是在那里返回,说,N-10**(-16)由于数值精度问题的情况下,在这种情况下int(numpy.sqrt(M))N-1

不过,我的测试有N==numpy.sqrt(M)返回True,所以它看起来像这种近似没有发生。

对于我来说假设int(numpy.sqrt(M))的确是准确的,当M是一个完美的正方形吗?如果是这样,为了奖金,在后台发生了什么事情使它起作用?

+1

号如果是float64,这将是正确的约20〜哪个地方*很多*,但并不完美。有办法采取int sqrt ... –

+0

请参阅http://stackoverflow.com/questions/15390858/weird-behaviour-of-np-sqrt-for-large-integers和http://stackoverflow.com/questions/15390807/integer-square-root-in-python – kennytm

回答

0

为了避免丢失由1E-15的整数,你可以使用:

int(numpy.sqrt(M)+0.5) 

int(round(numpy.sqrt(M))) 
+0

或者更明确地说:'int(round(np.sqrt(M)))' –

+0

@RobertKern谢谢。我总是想知道为什么'round()'不返回一个整数。 –

+1

从C处延缓。存在不能由任何C整数类型表示的整数“双”值。 Python 3.something has fixed that。 –