1. 使用`math.sqrt`函数求平方根:
```python
import math
求一个数的平方根
result = math.sqrt(16)
print(result) 输出:4.0
2. 使用幂运算符` `求平方根:
```python
求2的平方根
result = 2 0.5
print(result) 输出:1.30951
3. 对于二次方程,可以使用以下公式求根:
```python
import math
二次方程求根公式
a = float(input("请输入二次项系数:"))
b = float(input("请输入一次项系数:"))
c = float(input("请输入常数项:"))
delta = b2 - 4*a*c
if delta < 0:
print("方程无实根")
elif delta == 0:
x = -b / (2*a)
print("方程有一个实根:", x)
else:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
print("方程有两个实根:", x1, x2)
4. 对于更高次方程,可以使用`numpy`库中的`polyRoots`函数计算多项式的根:
```python
from numpy import polyRoots
多项式系数,例如 x^2 + 2x + 1 = 0
coefficients = [1, 2, 1]
roots = polyRoots(coefficients)
print(roots) 输出多项式的根
5. 对于一般的多项式方程,可以使用`evalPoly`函数结合`Laguerre`方法计算所有根:
```python
from evalPoly import *
from numpy import zeros, complex
from cmath import sqrt
def polyRoots(a, tol=1.0e-12):
def laguerre(a, tol):
x = random() 起始值(随机数)
n = len(a) - 1
for i in range(30):
p, dp, ddp = evalPoly(a, x)
if abs(p) < tol:
return x
g = f = p
while i < 29:
i += 1
p, dp, ddp = evalPoly(a, x + 1/i)
if abs(p) < tol:
return x
g = f
f = p
dx = n / (g + f)
x = x - p / dp
return x
x = laguerre(a, tol)
roots = [x]
for i in range(1, len(a)):
x = laguerre(a, tol)
if x not in roots:
roots.append(x)
return roots
以上方法可以帮助你在Python中求不同类型的方程的根。请根据你的具体需求选择合适的方法