2

Let's say I'm considering M=N**2 where N is an integer. It appears that numpy.sqrt(M) returns a float (actually numpy.float64).

I could imagine that there could be a case where it returns, say, N-10**(-16) due to numerical precision issues, in which case int(numpy.sqrt(M)) would be N-1.

Nevertheless, my tests have N==numpy.sqrt(M) returning True, so it looks like this approximation isn't happening.

Is it safe for me to assume that int(numpy.sqrt(M)) is indeed accurate when M is a perfect square? If so, for bonus, what's going on in the background that makes it work?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Joel
  • 22,598
  • 6
  • 69
  • 93
  • 1
    No. If it is a float64, it will be correct to approximately ~20 places which is *a lot*, but not perfect. There are ways to take the int sqrt... – Willem Van Onsem Feb 20 '17 at 19:06
  • See http://stackoverflow.com/questions/15390858/weird-behaviour-of-np-sqrt-for-large-integers and http://stackoverflow.com/questions/15390807/integer-square-root-in-python – kennytm Feb 20 '17 at 19:09

1 Answers1

2

To avoid missing the integer by 1E-15, you could use :

int(numpy.sqrt(M)+0.5)

or

int(round(numpy.sqrt(M)))
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124