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
    
  • 相关阅读:
    Android学习笔记——启动Activity及Activity生命周期
    TransposonPSI——转座子分析的入门自学
    关于 GraPhlAn 的孤独自学
    Javascript 正则表达式 子表达式
    关于set,list,map的理解
    js关于日期的操作
    JDBC和JTA事务区别
    远程调试本地服务或程序
    Fragment的数据传递
    记录自己的第一篇博客
  • 原文地址:https://www.cnblogs.com/imouren/p/2263967.html
Copyright © 2011-2022 走看看