黄金分割法 golden section search

改訂新版 C言語による標準アルゴリズム事典をSwiftでコーディング

アルゴリズム

黄金分割法 golden section search

実行

Playground

コード

import Foundation

func goldsect( a:inout Double, b:inout Double, tolerance:Double, f:((Double) -> Double)) -> Double {
    let r:Double = 2 / (3 + sqrt(5.0));
    if a > b {
        swap(&a, &b)
    }
    let t = r * (b - a)
    var c = a + t
    var d = b - t
    var fc = f(c)
    var fd = f(d)
    while(true) {
        if fc > fd {
            a = c
            c = d
            fc = fd
            d = b - r * (b - a)
            if d - c <= tolerance {
                return c
            }
            fd = f(d)
        }
        else {
            b = d
            d = c
            fd = fc
            c = a + r * (b - a)
            if d - c <= tolerance {
                return d
            }
            fc = f(c)
        }
    }
}

var a = 1.0
var b = 10.0
print("結果 = \(goldsect(a: &a, b: &b, tolerance: 0, f: {$0 * $0 - 2}))")

Algorithm,Swift

Posted by shi-n