/// OPTIMİZASYON
//  ÖDEV 1
import java.util.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import javax.swing.*;


public class OPO1a
{

public static double f(double x)
{
double a[]=new double[9];	
a[0] = 7.3596788873837795;
a[1] = 24.6295635541901;
a[2] = -28.17497179331258;
a[3] = 13.27506134507712;
a[4] = -3.1547062099562027;
a[5] = 0.409375615818135;
a[6] = -0.029361842858179443;
a[7] = 0.0010909188816725646;
a[8] = -1.6364232772847487E-5;
double f1=0;
f1=a[0]+a[1]*x+a[2]*x*x+a[3]*x*x*x+a[4]*x*x*x*x+a[5]*x*x*x*x*x+a[6]*x*x*x*x*x*x+a[7]*x*x*x*x*x*x*x+a[8]*x*x*x*x*x*x*x*x;
 return -f1;
}
	

public static double golden(double a,double b,double epsilon)
{return golden(a,b,epsilon,1.0e-10,0);}
public static double golden(double a,double b)
{return golden(a,b,1.0e-10,1.0e-10,0);}
public static double golden(double a,double b,double epsilon,double delta,int print)
{
//  f fonksiyonunun minimumunu bulur
// not  maximum f(x) = minimum (-f(x))
    double r1 = (Math.sqrt(5.0)-1.0)/2.0; // golden ratio
    double r2 = r1*r1;
    double h = b - a;
    double ya = f(a);
    double yb = f(b);
    double c = a + r2*h;
    double d = a + r1*h;
    double yc = f(c);
    double yd = f(d);
    int k = 1;
    double dp,dy,p,yp;
    while ((Math.abs(yb-ya)>epsilon) || (h>delta))
    {
      k++;
      if (yc<yd)
        {
        b = d;
        yb = yd;
        d = c;
        yd = yc;
        h = b - a;
        c = a + r2 * h;
        yc = f(c);
        }
      else
       {
         a = c;
         ya = yc;
         c = d;
         yc = yd;
         h = b - a;
         d = a + r1 * h;
         yd = f(d);
       }//end of if
    }//end of while
    dp = Math.abs(b-a);
    dy = Math.abs(yb-ya);
    p = a;
    yp = ya;
    if (yb<ya)
    {
      p = b;
      yp = yb;
    }
    if(print==1)
    {System.out.println("x min = "+p+"ymin = "+yp+"error of x ="+dp+"error of y"+dy); }
    return p;
}

     public static void main (String args[])  
     { 
     double a,b;
     a=Double.parseDouble(JOptionPane.showInputDialog(" Fonksiyonun alt sınırını giriniz a : "));
     b=Double.parseDouble(JOptionPane.showInputDialog(" Fonksiyonun üst sınırını giriniz b : "));
     double r;
     System.out.println("x=0.5"+f(0.5));
     System.out.println("x=1.5"+f(1.5));
     r= golden(a,b,1.0e-10,1.0e-5,0);
     JOptionPane.showMessageDialog(null," optimizasyon değeri  : "+r+"\nFonksiyon değeri : "+f(r),
     "Fibonacchi optimizasyon : ",JOptionPane.PLAIN_MESSAGE);
     System.exit(0);
     } 
}