美文网首页
python 函数模型(Functions as General

python 函数模型(Functions as General

作者: TFprime | 来源:发表于2019-03-11 19:24 被阅读0次

    函数模型

    参考:http://composingprograms.com/pages/16-higher-order-functions.html
    下面是一个函数的模版,意思是我们要求黄金数,大概是1.6,但是我们先随便猜一个数,如果这个数不满足close的条件,就update这个数,直到满足close的条件

    def improve(update, close, guess=1):
        while not close(guess):
            guess = update(guess)
        return guess
    

    完整的代码如下

    # -*- coding : utf-8 -*-
    
    def improve(update, close, guess=1):
        while not close(guess):
            guess = update(guess)
        return guess
    
    def golden_update(guess):
        return 1 / guess + 1
    
    def square_close_to_successor(guess):
        return approx_eq(guess * guess, guess + 1)
    
    def approx_eq(x, y, tolerance=1e-15):
        return abs(x - y) < tolerance
    
    golden_number = improve(golden_update, square_close_to_successor)
    print(golden_number)
    

    输出:

    1.6180339887498951
    

    相关文章

      网友评论

          本文标题:python 函数模型(Functions as General

          本文链接:https://www.haomeiwen.com/subject/mpqipqtx.html