牛顿迭代法求一个数的平方根(python)

# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: P♂boy
@License: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@Contact: [email protected]
@Software: Pycharm
@File: sqrt.py.py
@Time: 2018/11/19 16:22
@Desc:牛顿迭代法求一个数的平方根
1对给定正实数x和允许误差e,令变量y取任意正实数值,如另y=x
2如果y*y与x足够接近, 即|y*y-x|<e,计算结束并把y作为结果
3取z=(y+x/y)/2
4将z作为y的新值,回到步骤1
"""
import math
def sqrt(x):
    y = x
    while abs(y * y - x) > 1e-6:
        y = (y + x / y) / 2
    return y

print(sqrt(5))
print(math.sqrt(5))

结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43249914/article/details/84294886