Python : sqrt() 函數

  1. 開平方

函數 sqrt() 返回 x 的平方根(x > 0)

語法:

import math
math.sqrt( x )

注意: 此函數不可直接訪問,需要導入math模塊,然後需要使用math靜態對象調用此函數。

           參數 x -- 數值表達式

           返回結果是浮點數。

import math   # This will import math module

print "math.sqrt(100) : ", math.sqrt(100)
print "math.sqrt(7) : ", math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi)

# 輸出結果
math.sqrt(100) :  10.0    # 浮點
math.sqrt(7) :  2.64575131106
math.sqrt(math.pi) :  1.77245385091

實例1. 請利用filter()過濾出1~100中平方根是整數的數,即結果應該是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

import math

def is_sqr(x):
    r = int(math.sqrt(x))
    return r * r == x

print filter(is_sqr, range(1, 101))

 實例2. 

def find_next_square(sq):
    import math
    n = math.sqrt(sq)
    if int(sq)  == int(n) * int(n):     #此處解決了(整數與浮點數的問題)
        return (int((n+1)*(n+1)))
    else:
        return -1
print(find_next_square(4.0))

#輸出結果
9

2. 開n次方

利用pow(a, b)函數即可。需要開 a 的 r 次方則pow(a, 1.0/ r )。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章