Advertisement
Guest User

Untitled

a guest
May 24th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. import java.text.DecimalFormat;
  2.  
  3. public class Principal {
  4.  
  5.     public static void main (String[] args){
  6.         Min_Search_Golden_Section(0, 4, 0.1);
  7.     }
  8.  
  9.     static double f1 (double x){
  10.         return (5+2*(x-3)*(x-3));
  11.     }
  12.  
  13.     static double f (double x){
  14.         return ((x-2)*(x-2)+4); //Parabola
  15.     }
  16.  
  17.     static void Min_Search_Golden_Section(double a, double b, double tolerancia){
  18.          double mu = 0.382;  // 1/gama^2
  19.          double x1, x2;
  20.          double fx1, fx2;
  21.          int n = 2; // numero de pontos x calculados
  22.          DecimalFormat df2 = new DecimalFormat(".###");
  23.  
  24.          x1 = a + mu * (b - a);
  25.          x2 = b - mu * (b - a);
  26.          fx1 = f(x1);
  27.          fx2 = f(x2);
  28.  
  29.          System.out.println("n\t x1 \t x2 \t a \t b \tf(a) \tf(b)");
  30.          System.out.println(n+"\t"+df2.format(x1)+"\t"+df2.format(x2)+"\t"+df2.format(a)+"\t"+df2.format(b)+"\t"+df2.format(f(a))+"\t"+df2.format(f(b)));
  31.  
  32.         while ((b - a) > tolerancia && x1<x2) {
  33.             n++;
  34.             if (fx1 > fx2) {
  35.                 a = x1; // Descartar intervalo de a a x1
  36.                 x1 = x2;
  37.                 fx1 = fx2;
  38.                 //x2 = b - mu* (b - a); // Determinar novo ponto
  39.                 x2 = b + (a-x2);
  40.                 fx2 = f(x2);
  41.             } else if (fx2>fx1){
  42.                 b = x2; // Descartar intervalo de x2 a b
  43.                 x2 = x1;
  44.                 fx2 = fx1;
  45.                 //x1 = a + mu*(b - a); // Determinar novo ponto
  46.                 x1 = a + (b-x1);
  47.                 fx1 = f(x1);
  48.             } else {
  49.                 n++;
  50.                 b = x2; // Descartar intervalo de x2 a b e de a a x1
  51.                 a = x1;
  52.                 x2 = b - mu * (b - a);
  53.                 x1 = a + mu * (b - a);
  54.                 fx1 = f(x1);
  55.                 fx2 = f(x2);
  56.             }
  57.             System.out.println(n+"\t"+df2.format(x1)+"\t"+df2.format(x2)+"\t"+df2.format(a)+"\t"+df2.format(b)+"\t"+df2.format(f(a))+"\t"+df2.format(f(b)));
  58.         }
  59.         System.out.println("Resultado final "+n+"\t"+df2.format(x1)+"\t"+df2.format(x2)+"\t"+df2.format(f(a))+"\t"+df2.format(f(b)));
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement