Latest web development tutorials

Python square root

Document Object Reference Examples Python3

Square root, also known as the secondary root, expressed as [√¯], such as: mathematical language: √¯16 = 4. Language described as: root 16 = 4.

The following examples by the user to enter a number, and calculate the square root of this number:

# -*- 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))

Execute the above code output results:

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

In this example, we enter a number by a user, and use the index to calculate the square root operator ** Number of change.

The program applies only to a positive number. Negative and complex can use the following ways:

# -*- 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))

Execute the above code output results:

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

In this example, we used cmath (complex math) sqrt () method of the module.

Document Object Reference Examples Python3