zoukankan      html  css  js  c++  java
  • 开方实现

    一种是二分查找的使用

    二分法,在很多排序,查找等问题中经常使用

    def squareRootBi(x, epsilon):
        """Assume x >= 0 and epsilon > 0
           Return y s.t. y*y is within epsilon of x"""
        #假设x>=0且ε>0,返回y,使得y*y在x的ε内
        assert x >= 0, 'x必须为非负数,而不是' + str(x)
        assert epsilon > 0, 'ε必须为正数,而不是' + str(epsilon)
        low = 0
        high = x
        #high = max(x,1)
        guess = (low + high)/2.0
        ctr = 1
        while abs(guess**2 - x) > epsilon and ctr <= 100:
            #print 'low:', low, 'high:', high, 'guess:', guess
            if guess**2 < x:
                low = guess
            else:
                high = guess
            guess = (low + high)/2.0
            ctr += 1
        assert ctr <=100, '循环计数次数超出范围'
        print 'Bi方法,循环数', ctr, '估值', guess
        return guess
    

    另外一种,是求切点的值的思路,使用了牛顿迭代法

    def squareRootNR(x, epsilon):
        """Assume x >= 0 and epsilon > 0
           Return y s.t. y*y is within epsilon of x"""
        #假设x>=0且ε>0,返回y,使得y*y在x的ε内
        assert x >= 0, 'x必须为非负数,而不是' + str(x)
        assert epsilon > 0, 'ε必须为正数,而不是' + str(epsilon)
        x = float(x)
        guess = x/2.0
        #guess = 0.001
        diff = guess**2 -x
        ctr = 1
        while abs(diff) > epsilon and ctr <= 100:
            #print '差值:', diff, '猜想值:', guess
            guess = guess - diff/(2.0*guess)
            diff = guess**2 - x
            ctr += 1
        assert ctr <=100, '循环计数次数超出范围'
        print 'NR方法,循环数', ctr, '估值', guess
        return guess
    
  • 相关阅读:
    置顶
    hbck2的一些用法
    常用的jvm一些监控命令
    HBCK2修复hbase2的常见场景
    HBase2版本的修复工具HBCK2
    使用python写入excel
    CentOS-Linux下面的xfs磁盘配额
    使用podman容器部署飞儿云框架
    在docker中安装宝塔
    在CentOS7中安装Docker并开一台CentOS8的容器
  • 原文地址:https://www.cnblogs.com/imouren/p/2263967.html
Copyright © 2011-2022 走看看