# !/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))
結果