// NA29 Newton Raphson method
// to solve non-lineer system of equation

import java.util.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import javax.swing.*;
//============= Tanımı gereken fonksiyon ================

class fa extends fi_xi
{
public double[] func(double x[])
{
//system of non-lineer equation	
double ff[]=new double[3];
ff[0]=x[0]*x[0]+x[0]*x[1]-10.0;
ff[1]=x[1]+3.0*x[0]*x[1]*x[1]-57.0;
ff[2]=x[2]-4;
return ff;
} 
}

class fb extends fij_xi
{
//derivative of system of non-lineer equation
public double[][] func(double x[])
{	
double a[][]=new double[3][3];
a[0][0]=2.0*x[0]+x[1];
a[0][1]=x[0];
a[0][2]=0.0;
a[1][0]=3.0*x[1]*x[1];
a[1][1]=1.0+6.0*x[0]*x[1];
a[1][2]=0.0;
a[2][0]=0;
a[2][1]=0;
a[2][2]=1.0;
return a;
} 
}


public class NA29
{
// Roots of system of non-lineer equations
// By using Newton-Raphson Method

public static double[] newton(fi_xi f,fij_xi df,double x[])
{
//x vector of independent variables
//y vector of dependent variable
//dy derivative of vector of dependent variable
double ti=1.0;
int i;
int nmax=400;
double tolerance=1.0e-5;
int n=x.length;
double b[];
b=new double[n];
for(i=0;i<n;i++)
{
b[i]=1.0;
}
i=0;
while( i++ < nmax && Matrix.abs(b) > tolerance )
{ b=Matrix.multiply(Matrix.divide(f.func(x),df.func(x)),-1.0); 
  x=Matrix.add(x,b);
  System.out.println(Matrix.toString(x));
}
if(i >= nmax) JOptionPane.showMessageDialog(null,"Maximum number of iterations are exceeded \n"+
              " Results might not be valid","MAXIMUM NUMBER OF ITERATIONS ERROR",JOptionPane.WARNING_MESSAGE);
System.out.println();
return x;
}

public static double[] verigir()
{
    String s=JOptionPane.showInputDialog("ENTER FIRST ROOT ESTIMATES WİTH ONE EMPTY SPPACE IN BETWEEN: ");        
    StringTokenizer token=new StringTokenizer(s);
    int n=token.countTokens()-1;
    int m=n+1;
    double a[]=new double[m];
    int j=0;           
    while(token.hasMoreTokens())
    {
    Double ax=new Double(token.nextToken());
    a[j++]=ax.doubleValue();
    }
    return a; 
}

     public static void main (String args[])  
     {
	 fa f =new fa();
     fb df=new fb();
     double [] x0=verigir();
     double [] r= newton(f,df,x0);
     String s=" Root values  : \n"+Matrix.toStringT(r)+"\n";
     s+="function values = "+Matrix.toStringT(f.func(r));
     String s1="Finding roots of the multivariable non-lineer system of equations : ";
     JOptionPane.showMessageDialog(null,s,s1,JOptionPane.PLAIN_MESSAGE);
     System.exit(0);
     } 
}