//
// 
//  
// Brent root finding method
//  
//  
import java.util.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import javax.swing.*;

class fc extends f_x
{
public double func(double x)
{return (x+3)*(x-1)*(x-1);}
}

public class NA13A
{

public static double brent(f_x f,double x1,double x2)
{
    // roots of the nonlinear equation: Brent method
    // referance : Numerical Recipes in C, second edition, William H. Press, 
    // Saul A. Teukolsky, William T. Vetterling, Brian P. Flannery
    // cambridge university press	
	double ITMAX=100;
    double EPS=3.0e-8;
	int iter;
	double a=x1,b=x2,c,d,e,min1,min2;
	double tol=1.0e-5;
	c=0;
	d=0;
	e=0;
	double fa=f.func(a),fb=f.func(b),fc,p,q,r,s,tol1,xm;
	if (fb*fa > 0.0) JOptionPane.showMessageDialog(null,"Root limit selection is uncorrect \n result may be wrong"
	,"ROOT LIMITS WARNING",JOptionPane.WARNING_MESSAGE);
	fc=fb;
	for (iter=1;iter<=ITMAX;iter++) {
		if (fb*fc > 0.0) {
			c=a;
			fc=fa;
			e=d=b-a;
		}
		if (Math.abs(fc) < Math.abs(fb)) {
			a=b;
			b=c;
			c=a;
			fa=fb;
			fb=fc;
			fc=fa;
		}
		tol1=2.0*EPS*Math.abs(b)+0.5*tol;
		xm=0.5*(c-b);
		if (Math.abs(xm) <= tol1 || fb == 0.0) return b;
		if (Math.abs(e) >= tol1 && Math.abs(fa) > Math.abs(fb)) {
			s=fb/fa;
			if (a == c) {
				p=2.0*xm*s;
				q=1.0-s;
			} else {
				q=fa/fc;
				r=fb/fc;
				p=s*(2.0*xm*q*(q-r)-(b-a)*(r-1.0));
				q=(q-1.0)*(r-1.0)*(s-1.0);
			}
			if (p > 0.0)  q = -q;
			p=Math.abs(p);
			min1=3.0*xm*q-Math.abs(tol1*q);
			min2=Math.abs(e*q);
			if (2.0*p < (min1 < min2 ? min1 : min2)) {
				e=d;
				d=p/q;
			} else {
				d=xm;
				e=d;
			}
		} else {
			d=xm;
			e=d;
		}
		a=b;
		fa=fb;
		if (Math.abs(d) > tol1)
			b += d;
		else
			b += (xm > 0.0 ? Math.abs(tol1) : -Math.abs(tol1));
		fb=f.func(b);
	}
JOptionPane.showMessageDialog(null,"Maximum number of iterations are exceeded \n"+
   " Result mAy not be valid","MAXIMUM ITERATION NUMBER WARNING",JOptionPane.WARNING_MESSAGE);
return b;
}

     public static void main (String args[])  
     { 
     double a,b;
     
     a=Double.parseDouble(JOptionPane.showInputDialog(" Enter lower limit of the function a : "));
     b=Double.parseDouble(JOptionPane.showInputDialog(" Enter upper limit of the function  b : "));
     double r;
     fc f=new fc();
     r= brent(f,a,b);
     JOptionPane.showMessageDialog(null," root value (x)  : "+r+"\nfunction value f(x) : "+f.func(r),
     "Root finding by using brent method : ",JOptionPane.PLAIN_MESSAGE);
     System.exit(0);
     } 
}
