/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.text.*;
/*
 * NewJApplet.java
 *
 * Created on 16.03.2010, 17:28:58
 */

/**
 *
 * @author poj
 */
public class NewJApplet extends javax.swing.JApplet {

    double xx = 0.3;
    int nmax = 25;
    double lower = 0.0;
    double upper=Math.PI*Math.PI;
    double x, y, h, h2, h3, d1, d2, d3, d0, d00, dex, denom, fi0, fik;
    double[][] p;
    double[] pow2, err1, err2;
    int i, j, k, i0, ik;
    long count, nb;
    int ndone=0;
    int funcsel=0;
    int metsel=0;
    double epsilon=0.1;

    /** Initializes the applet NewJApplet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {

                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        p = new double[nmax][nmax];
        pow2 = new double[nmax];
        err1 = new double[nmax];
        err2 = new double[nmax];
        jLabel1.setText("iter="+0+" f values="+0);
        jLabel2.setText("eps=10^ "+0);
    }

    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new myPanel();
        jLabel1 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jSlider1 = new javax.swing.JSlider();
        jLabel2 = new javax.swing.JLabel();
        jRadioButton4 = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setPreferredSize(new java.awt.Dimension(202, 200));
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("GO!");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 577, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 413, Short.MAX_VALUE)
        );

        jLabel1.setText("jLabel1");

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setSelected(true);
        jRadioButton1.setText("int(sin(x^2),0,pi^2)");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setText("int(x^ -1/2 ,epsilon,1)");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        buttonGroup2.add(jRadioButton3);
        jRadioButton3.setSelected(true);
        jRadioButton3.setText("trapezoidal");
        jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton3ActionPerformed(evt);
            }
        });

        jSlider1.setMajorTickSpacing(1);
        jSlider1.setMaximum(0);
        jSlider1.setMinimum(-10);
        jSlider1.setPaintLabels(true);
        jSlider1.setPaintTicks(true);
        jSlider1.setSnapToTicks(true);
        jSlider1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jSlider1MouseDragged(evt);
            }
        });

        jLabel2.setText("jLabel2");

        buttonGroup2.add(jRadioButton4);
        jRadioButton4.setText("midpoint");
        jRadioButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton4ActionPerformed(evt);
            }
        });

        jLabel3.setText("error of numerical integration");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jRadioButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jRadioButton2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jRadioButton3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jRadioButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(133, 133, 133)
                                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 704, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 133, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(239, 239, 239)
                .addComponent(jLabel3)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jRadioButton1)
                            .addComponent(jRadioButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jRadioButton3)
                            .addComponent(jRadioButton4)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)))
                .addGap(66, 66, 66))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        romberg();
        jPanel1.repaint();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
      funcsel=0;
      lower=0.0;
      upper = Math.PI * Math.PI;// TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jSlider1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSlider1MouseDragged
        int n;
        n=jSlider1.getValue();
        epsilon=1./Math.pow(10,-n);
        jLabel2.setText("eps=10^ "+n);
    }//GEN-LAST:event_jSlider1MouseDragged

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
      funcsel=1;
      lower=epsilon;
      upper = 1.0;// TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton2ActionPerformed

    private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed
      metsel=0;  // TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton3ActionPerformed

    private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton4ActionPerformed
       metsel=1; // TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton4ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
    public double f(double x) {
        double y;
        count++;

        if(funcsel==0) y = Math.sin(x * x); else y=1.0/Math.sqrt(x);
        return y;
    }

    double tr(long nb) {
        return 0;
    }


    public double midpoint(long numb)
{
  double x_t,y_t;




  double sum;
  int i;



  sum=0;
  h=(upper-lower)/(double)numb;

  for(i=0;i<numb;i++)
    {
      x_t=lower+(i+0.5)*h;
      y_t=f(x_t);

      sum=sum+y_t;


    }

  sum=sum*h;


  return sum;
}




    double trapez(long nb) // composite trapezoidal rule
    // nb is the number of bins
    {
        double x_t, y_t, h;

        double sum;
        int i;

        sum = 0.5 * (f(lower) + f(upper));
        h = (upper - lower) / nb;

        x_t = lower + h;

        for (i = 1; i < nb; i++) {

            x_t = lower + i * h;
            y_t = f(x_t);
            sum = sum + y_t;
        }

        sum = sum * h;


        return sum;
    }

    public void romberg() {

        Graphics g;
        int aw,ah,ix,iy;
        jTextArea1.selectAll();
        jTextArea1.replaceSelection("romberg integration\n");


        if(funcsel==0){lower=0; upper=Math.PI*Math.PI;}
        else{lower=epsilon; upper=1.0;}

        jTextArea1.append("function= "+funcsel+"  method= "+metsel+" range "+lower+"  "+upper+"\n");

        g=jPanel1.getGraphics();
          ah = jPanel1.getHeight();
        aw = jPanel1.getWidth();
        clearcanvas();

        // this is the exact value
        double dex;


        if(funcsel==0) dex= 0.6773089370468890331;
        else dex=2.*Math.sqrt(1.0)-2.*Math.sqrt(epsilon);


        
        
        count=0;
        // the starting number
        ndone=0;
        nb = 4;
        pow2[0] = 1;
        for (i = 1; i < nmax; i++) {
            pow2[i] = pow2[i - 1] * 2;
        }


        jTextArea1.append(" exact value =" + dex + "  \n");
        
        if(metsel==0)
        jTextArea1.append("iter   error of extrapolation   of comp. trapezoidal rule \n");
         else
        jTextArea1.append("iter   error of extrapolation   of comp. midpoint rule \n");
            
        for (i = 0; i < nmax; i++) {
            for (j = 0; j < nmax; j++) {
                p[i][j] = 0.0;
            }
        }

        for (i = 0; i < nmax; i++) {


            if(metsel==0)
            p[i][0] = trapez(nb);
            else
            p[i][0] = midpoint(nb);
            
            err2[i] = (p[i][0] - dex);

            jLabel1.setText("iter="+i+" f values="+count);
            jLabel1.paintImmediately(0,0, 400, 20);

              g.setColor(Color.BLUE);
             ix = 40+i * 20;
                iy = 40 - (int) (Math.log10(Math.abs(err2[i])) * 20);
                g.fillOval(ix-3, iy-3, 6, 6);

            // double the number of bins
            nb = nb * 2;

        }

        for (j = 1; j < nmax; j++) {
            for (i = 0; i < nmax - j; i++) {



                denom = 1.0 / (1.0 - pow2[j] * pow2[j]);

                p[i][j] = p[i + 1][j - 1] + (p[i][j - 1] - p[i + 1][j - 1]) * denom;


            }

            err1[j] = (p[0][j] - dex);

              g.setColor(Color.RED);
             ix = 40+j * 20;
                iy = 40 - (int) (Math.log10(Math.abs(err1[j])) * 20);
                if(Math.abs(err1[j])>0) g.fillOval(ix-3, iy-3, 6, 6);


            ndone=j+1;

            //jPanel1.paintImmediately(0, 0, aw, ah);
          
              // jPanel1.paintImmediately(0, 0, aw, ah);

            jTextArea1.append("" + j + "  " + err1[j] + "  " + err2[j] + "\n");
             

            ah = jTextArea1.getHeight();
            aw = jTextArea1.getWidth();
            jTextArea1.paintImmediately(0, 0, aw, ah);

        }



        // print absolute error of extrapolated values
        // and trapezoidal sums

      



    }

    public void clearcanvas()
    {
     int i, ix, iy,aw,ah;
        Graphics g;
        g=jPanel1.getGraphics();
        g.setColor(Color.lightGray);
        ah = jPanel1.getHeight();
        aw = jPanel1.getWidth();
        g.clearRect(0, 0, aw, ah);

          g.setColor(Color.BLACK);

            for (i = 0; i < 25; i++) {

                ix = 40+i * 20;
                g.drawLine(ix, 20, ix, 360);

                g.drawString("" + i, ix - 4, 380);
            }
            for (i = -1; i < 17; i++) {

                iy = 40 + i * 20;
                g.drawLine(40, iy, 520, iy);

                if(i<=0)  g.drawString("E+" + (-i), 0, iy);
                else
                g.drawString("E-" + i, 0, iy);


            }
             g.drawString("iterations",250,400);
            g.drawString("red=extrapolation",300,420);
            
             if(metsel==0) g.drawString("blue=composite trapezoidal",50,420);
                   else g.drawString("blue=composite midpoint",50,420);
                   
            
    }

    public class myPanel extends javax.swing.JPanel {

        int i, ix, iy,aw,ah;

        public void paintComponent(Graphics g) {

            int ip;


            super.paintComponent(g);
  g.setColor(Color.lightGray);
        ah = jPanel1.getHeight();
        aw = jPanel1.getWidth();
        g.clearRect(0, 0, aw, ah);
            clearcanvas();
       
            g.setColor(Color.RED);
            for (j = 0; j < ndone; j++) {

                ix = 40+j * 20;
                iy = 40 - (int) (Math.log10(Math.abs(err1[j])) * 20);
                 if(Math.abs(err1[j])>0)  g.fillOval(ix-3, iy-3, 6, 6);


            }
            g.setColor(Color.BLUE);
            for (j = 0; j < ndone; j++) {

                ix = 40+j * 20;
                iy = 40 - (int) (Math.log10(Math.abs(err2[j])) * 20);
                g.fillOval(ix-3, iy-3, 6, 6);


            }
               g.setColor(Color.BLACK);

            for (i = 0; i < 25; i++) {

                ix = 40+i * 20;
                g.drawLine(ix, 20, ix, 360);

                g.drawString("" + i, ix - 4, 380);
            }
            for (i = -1; i < 17; i++) {

                iy = 40 + i * 20;
                g.drawLine(40, iy, 520, iy);

                if(i<=0)  g.drawString("E+" + (-i), 0, iy);
                else
                g.drawString("E-" + i, 0, iy);


            }
                   g.drawString("iterations",250,400);
                   if(metsel==0) g.drawString("blue=composite trapezoidal",50,420);
                   else g.drawString("blue=composite midpoint",50,420);
                   
                   
                   g.drawString("red=extrapolation",300,420);
              

        }
    }
}
