Skip to main content

ternary_search_max

Function ternary_search_max 

Source
pub fn ternary_search_max<F: Fn(f64) -> f64>(
    lo: f64,
    hi: f64,
    eps: f64,
    f: F,
) -> f64
Expand description

Ternary search — unimodal (avval o’sib, keyin kamayadigan) funksiya maksimumi.

G’oya: oraliqni har qadamda uchga bo’lib, maksimum bo’lishi mumkin bo’lmagan uchdan birini tashlab yuboramiz.

eps — kerakli aniqlik. Qaytadi: maksimum bo’lgan x.

  • Time: O(log((hi-lo)/eps)), Space: O(1).

§Misol

use rust_algorithms::searching::ternary_search_max;

// f(x) = -(x-3)^2 + 10 → maksimum x = 3 da
let x = ternary_search_max(-10.0, 10.0, 1e-9, |x| -(x - 3.0) * (x - 3.0) + 10.0);
assert!((x - 3.0).abs() < 1e-5);