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


public class OPO1
{

public static double f(double x)
{
double xi[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,15};
double yi[]={7.5,13.5,12.7,9.8,11.9,14.7,13.6,8.7,5.9,8.9,13.7,14.8,13.9,8.9,7.6};
double f1=0;
for (int i=1;i<(xi.length-1);i++)	
	{if(x<=xi[i+1])
	  {
		f1=(x-xi[i])*(x-xi[i+1])/(xi[i-1]-xi[i])/(xi[i-1]-xi[i+1])*yi[i-1]+
		(x-xi[i-1])*(x-xi[i+1])/(xi[i]-xi[i-1])/(xi[i]-xi[i+1])*yi[i]+
		(x-xi[i-1])*(x-xi[i])/(xi[i+1]-xi[i-1])/(xi[i+1]-xi[i])*yi[i+1];
	  break;
	  }
	}
 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);
     } 
}