Python中的平方根计算

Python提供了不同的函数和操作符来计算给定数字的平方根。这个数字可以是正数、负数、零、实数或复数。还有Numpy图书馆提供 sqrt() 函数来计算平方根。

null

数学模块sqrt()函数

最著名和流行的功能是 sqrt() 由提供的功能 math 模块或库。我们可以只提供我们想要计算这个函数平方根的数字。在下面的示例中,我们将导入 math 然后使用sqrt()函数。

import math

math.sqrt(25)
//Result will be 5.0

math.sqrt(9)
//Result will be 3.0

math.sqrt(90)
//Result will be 9.486832980505138

math.sqrt(900)
//Result will be 30.0

math.sqrt(90000)
//Result will be 300.0

math.sqrt(49)
//Result will be 7.0
Math Module sqrt() Function
数学模块sqrt()函数

零的平方根

零是一个特殊的数字,它可以根据不同的运算产生不同的结果。当我们取0的平方根时,结果就是0。

import math

math.sqrt(0)
//The result is 0.0

math.sqrt(0.0)
//The result is 0.0
Square Root of Zero
零的平方根

浮点数的平方根

浮点数不同于十进制数。它们提供了一些浮点部分,在计算平方根时可能会造成混淆。在本例中,我们将查看计算浮点数的示例。

import math

math.sqrt(9.9)
// Result is 3.146426544510455

math.sqrt(9.0)
// Result is 3.0

math.sqrt(9.9225)
// Result is 3.15

math.sqrt(99.81)
// Result is 9.990495483208027

math.sqrt(111.408025)
// Result is 10.555
Square Root Of Floating-Point Numbers
浮点数的平方根

负数的平方根

任何实数的平方都不能为负。因此,如果我们试图得到一个负数的平方根,我们会得到一个与数学域有关的错误,如下面所示。

import math

math.sqrt(-25)

math.sqrt(-0)
Square Root of Negative Numbers
负数的平方根

有趣的是,如果我们试着把0作为一个负数平方根,我们会得到0。因为零不能是正的也不能是负的。对于其他负数,我们将得到 ValueError math domain error .

数学模块pow()函数

math 模块还提供 pow() 用于计算给定数字的平方的函数。还有 ** 运算符,与 pow() 功能。我们将提供号码和 1/2 作为平方根数。

import math

math.pow(9,1/2)
//The result is 3.0

math.pow(9,0.5)
//The result is 3.0

math.pow(99.81,0.5)
//The result is 9.990495483208027

math.pow(111.408025,0.5)
//The result is 10.555

math.pow(111.408025,1/2)
//The result is 10.555
Math Module pow() Function
数学模块pow()函数

实数或复数平方根

我们也可以计算实数或复数的平方根 cmath 使用前应导入的库。在这些示例中,我们将提供实数,如 1+2j , 5+10j 等。

import cmath

cmath.sqrt(1+2j)
//The result is (1.272019649514069+0.7861513777574233j)

cmath.sqrt(10+2j)
//The result is (3.177895453534113+0.3146736620576702j)

cmath.sqrt(10+20j)
//The result is (4.022479320953552+2.486028939392892j)

cmath.sqrt(9+9j)
//The result is (3.29605234040343+1.365269581686682j)


cmath.sqrt(64+25j)
//The result is (8.14584352738277+1.5345249338488343j)
Real or Complex Numbers Square Root
实数或复数平方根

用平方算子计算平方根

数学很神奇,我们可以用不同的方式表达不同的计算。我们可以使用平方运算符来计算平方根。广场 ** 运算符与 1/2 计算平方根的数字。我们也可以使用 0.5 根据 1/2 这是一个相同的价值观与不同的介绍。

a = (9)**(1/2)
// The result is 3.0

a=(100)**(1/2)
// The result is 10.0

a=(64)**(1/2)
// The result is 8.0

a=(64)**(0.5)
// The result is 8.0

a=(99.81)**(0.5)
// The result is 9.990495483208027

a=(111.408025)**(0.5)
// The result is 10.555
Square Root Calculation with Square Operator
用平方算子计算平方根

Numpy sqrt()函数

numpy 是第三方库和模块,提供矩阵、级数、大数据等计算,Numpy还提供sqrt()和pow()函数,我们可以用这些函数来计算平方根。

import numy

numpy.sqrt(9)
//The result is 3

numpy.pow(9,1/2)
//The result is 3
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享