Python sqrt()函數(shù)用法說明
函數(shù) sqrt() 返回 x 的平方根(x > 0)
語法:
import mathmath.sqrt( x )
注意:此函數(shù)不可直接訪問,需要導入math模塊,然后需要使用math靜態(tài)對象調(diào)用此函數(shù)。
參數(shù) x -- 數(shù)值表達式
返回結果是浮點數(shù)。
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.64575131106math.sqrt(math.pi) : 1.77245385091實例1.
請利用filter()過濾出1~100中平方根是整數(shù)的數(shù),即結果應該是:
[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): #此處解決了(整數(shù)與浮點數(shù)的問題) return (int((n+1)*(n+1))) else: return -1print(find_next_square(4.0)) #輸出結果2、開n次方
利用pow(a, b)函數(shù)即可。需要開 a 的 r 次方則pow(a, 1.0/ r )。
補充:python中sqrt函數(shù)用法_sqrt是什么函數(shù)
sqrt是什么函數(shù)?sqrt()是用于計算數(shù)字x的平方根的函數(shù)。
語法
以下是 sqrt() 方法的語法:import math
math.sqrt( x )
注意:sqrt()是不能直接訪問的,需要導入 math 模塊,通過靜態(tài)對象調(diào)用該方法。
參數(shù)x -- 數(shù)值表達式。
返回值返回數(shù)字x的平方根。
實例以下展示了使用 sqrt() 方法的實例:
#!/usr/bin/pythonimport math # This will import math moduleprint '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.0math.sqrt(7) : 2.64575131106math.sqrt(math.pi) : 1.77245385091
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
