牛頓迭代法求一個數的平方根(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))

結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章