Python对正数开方的两种方法

本文介绍如何使用Python编程语言实现二分法和Newton-Raphson法来精确计算正数的平方根,通过设置精度参数epsilon,确保计算结果的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用Python实现二分法以及Newton-Raphson法对正数进行开方

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 10:14:14 2019

@author: Zha_Jiajia
"""

def SquarerootBi(x, epsilon):
    '''Return the squareroot of a nonnegative number x 
    with the precision epsilon'''
    assert x >= 0, '%f is not a nonnegative number' %x
    assert epsilon > 0, '%f is not a positive number' %epsilon
    low = 0
    high = x
    guess = (low + high) / 2
    ctn = 1
    while abs(guess**2 - x) >= epsilon and ctn < 100:
        if guess**2 > x: 
            high = guess
            guess = (low + high) / 2
        else: 
            low = guess
            guess = (low + high) / 2
        ctn += 1
    print("SquarerootBI, Iteration time: %i, Answere: %f" %(ctn, guess))
    
def SquarerootNR(x, epsilon):
    '''Return the squareroot of a nonnegative number x 
    with the precision epsilon'''
    assert x >= 0, '%f is not a nonnegative number' %x
    assert epsilon > 0, "%f is not a positive number" %epsilon
    guess = epsilon
    ctn = 1
    while abs(guess**2 -x) >= epsilon and ctn < 100:
        guess = (x - guess**2) / (2 * guess) + guess
        ctn += 1
    print("SquarerootNR, Iteration time: %i, Answere: %f" %(ctn, guess))
    
if __name__ == "__main__":
    SquarerootBi(1e7, 0.001)
    input()
    SquarerootNR(1e7, 0.001)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值