Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.04 KB | None | 0 0
  1. #![feature(non_ascii_idents)]
  2. #![feature(associated_consts)]
  3.  
  4. const φ: f64 = 1.618033988749894848204586834365638117720309179805762862135;
  5.  
  6. trait Foo {
  7.     type FooType;
  8.     type FooKek;
  9.     type KekTyt;
  10.     fn bar();
  11.     fn foo();
  12.     const A: i32;
  13. }
  14.  
  15. #[derive(Debug)]
  16. struct Bar;
  17.  
  18. impl Foo for Bar {
  19.  
  20. }
  21.  
  22. fn main() {
  23.     let f = |x: f64| x * x * x * x + x * x * x - 7.0 * x * x - x + 1.0;
  24.     let g = |x, y| -48.0 * x + 6.0 * x * x - 42.0 * y + 21.0 * y * y
  25.         + 16.0 * x * y - 2.0 * x * x * y - 8.0 * x * y * y + x * x * y * y;
  26.     println!("{:?}", plane_search(&g, 0.0, 0.0, 10.0, 0.1));
  27. }
  28.  
  29. fn golden_search<F>(f: &F, mut left: f64, mut right: f64) -> f64 where F: Fn(f64) -> f64 {
  30.     let mut y1 = None;
  31.     let mut y2 = None;
  32.     while right - left > 1e-7 {
  33.         let x1 = right - (right - left) / φ;
  34.         let x2 = left + (right - left) / φ;
  35.         if let None = y1 {
  36.             y1 = Some((*f)(x1));
  37.         }
  38.         if let None = y2 {
  39.             y2 = Some((*f)(x2));
  40.         }
  41.         if y1.unwrap() < y2.unwrap() {
  42.             right = x2;
  43.             y2 = y1;
  44.             y1 = None;
  45.         } else {
  46.             left = x1;
  47.             y1 = y2;
  48.             y2 = None;
  49.         }
  50.     }
  51.     (left + right) / 2.0
  52. }
  53.  
  54. fn global_search<F>(f: &F, left: f64, right: f64, step: f64) -> f64 where F: Fn(f64) -> f64 {
  55.     let mut x_min_glob = 0.0;
  56.     let mut y_min_glob = std::f64::INFINITY;
  57.     let mut x = left;
  58.     while x < right {
  59.         let x_min = golden_search(&f, x as f64, x as f64 + 1.0);
  60.         let y_min = f(x_min);
  61.         if y_min < y_min_glob {
  62.             y_min_glob = y_min;
  63.             x_min_glob = x_min;
  64.         }
  65.         x += step;
  66.     }
  67.     x_min_glob
  68. }
  69.  
  70. fn plane_search<G>(g: &G, mut cx: f64, mut cy: f64, range: f64, step: f64) -> (f64, f64)
  71.     where G: Fn(f64, f64) -> f64 {
  72.     for _ in 1..20 {
  73.         cx = global_search(&|x| (*g)(x, cy), cx - range, cx + range, step);
  74.         cy = global_search(&|y| (*g)(cx, y), cy - range, cy + range, step);
  75.     }
  76.     (cx, cy)
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement