Latest web development tutorials

Python 平方根

Document 對象參考手冊 Python3實例

平方根,又叫二次方根,表示為〔√ ̄〕,如:數學語言為:√ ̄16=4。 語言描述為:根號下16=4。

以下實例為通過用戶輸入一個數字,併計算這個數字的平方根:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3big.com

num = float(input('请输入一个数字: '))
num_sqrt = num ** 0.5
print(' %0.3f 的平方根为 %0.3f'%(num ,num_sqrt))

執行以上代碼輸出結果為:

$ python test.py 
请输入一个数字: 4
 4.000 的平方根为 2.000

在該實例中,我們通過用戶輸入一個數字,並使用指數運算符** 來計算改數的平方根。

該程序只適用於正數。 負數和復數可以使用以下的方式:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3big.com

# 计算实数和复数平方根
# 导入复数数学模块

import cmath

num = int(raw_input("请输入一个数字: "))
num_sqrt = cmath.sqrt(num)
print('{0} 的平方根为 {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

執行以上代碼輸出結果為:

$ python test.py 
请输入一个数字: -8
-8 的平方根为 0.000+2.828j

該實例中,我們使用了cmath (complex math) 模塊的sqrt() 方法。

Document 對象參考手冊 Python3實例