Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![feature(non_ascii_idents)]
- #![feature(associated_consts)]
- const φ: f64 = 1.618033988749894848204586834365638117720309179805762862135;
- trait Foo {
- type FooType;
- type FooKek;
- type KekTyt;
- fn bar();
- fn foo();
- const A: i32;
- }
- #[derive(Debug)]
- struct Bar;
- impl Foo for Bar {
- }
- fn main() {
- let f = |x: f64| x * x * x * x + x * x * x - 7.0 * x * x - x + 1.0;
- let g = |x, y| -48.0 * x + 6.0 * x * x - 42.0 * y + 21.0 * y * y
- + 16.0 * x * y - 2.0 * x * x * y - 8.0 * x * y * y + x * x * y * y;
- println!("{:?}", plane_search(&g, 0.0, 0.0, 10.0, 0.1));
- }
- fn golden_search<F>(f: &F, mut left: f64, mut right: f64) -> f64 where F: Fn(f64) -> f64 {
- let mut y1 = None;
- let mut y2 = None;
- while right - left > 1e-7 {
- let x1 = right - (right - left) / φ;
- let x2 = left + (right - left) / φ;
- if let None = y1 {
- y1 = Some((*f)(x1));
- }
- if let None = y2 {
- y2 = Some((*f)(x2));
- }
- if y1.unwrap() < y2.unwrap() {
- right = x2;
- y2 = y1;
- y1 = None;
- } else {
- left = x1;
- y1 = y2;
- y2 = None;
- }
- }
- (left + right) / 2.0
- }
- fn global_search<F>(f: &F, left: f64, right: f64, step: f64) -> f64 where F: Fn(f64) -> f64 {
- let mut x_min_glob = 0.0;
- let mut y_min_glob = std::f64::INFINITY;
- let mut x = left;
- while x < right {
- let x_min = golden_search(&f, x as f64, x as f64 + 1.0);
- let y_min = f(x_min);
- if y_min < y_min_glob {
- y_min_glob = y_min;
- x_min_glob = x_min;
- }
- x += step;
- }
- x_min_glob
- }
- fn plane_search<G>(g: &G, mut cx: f64, mut cy: f64, range: f64, step: f64) -> (f64, f64)
- where G: Fn(f64, f64) -> f64 {
- for _ in 1..20 {
- cx = global_search(&|x| (*g)(x, cy), cx - range, cx + range, step);
- cy = global_search(&|y| (*g)(cx, y), cy - range, cy + range, step);
- }
- (cx, cy)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement