if graph == square_grid and type(math.sqrt(nodes)) is not int:
print "Your netork can't have that number of nodes"
當然,這並不工作,因爲math.sqrt總是返回一個浮點數。我怎樣才能做到這一點?
if graph == square_grid and type(math.sqrt(nodes)) is not int:
print "Your netork can't have that number of nodes"
當然,這並不工作,因爲math.sqrt總是返回一個浮點數。我怎樣才能做到這一點?
一種方法是
int(math.sqrt(x)) ** 2 == x
因爲math.sqrt總是返回一個浮點數,你可以使用內置的is_integer
方法
def is_square(x):
answer = math.sqrt(x)
return answer.is_integer()
這將返回True
如果x
是一個正方形和False
如果它不是
>>> is_square(25)
True
>>> is_square(14)
False
嘗試:
math.sqrt(nodes) == int(math.sqrt(nodes))
嗯。由於在計算過程中出現四捨五入錯誤,將浮點數視爲不精確,是否會發生方數的sqrt()最終不會成爲整數?這會讓@ larsmans的回答更好。 – millimoose 2013-05-07 18:54:24
這是一個有效的點,但我只是運行了一個for循環,使用這種方法可以打印出所有有效的正方形高達100,000,並且它不會錯過任何一個。 – 2013-05-07 19:04:10
整數完全以浮點形式表示(它們在點之後全部爲零)。不過,我不確定'sqrt'是否可以保證這一點。 – 2013-05-07 19:18:59