1   import fi.jyu.mit.ohj2.*;
2   /**
3    * Ohjelmalla integroidaan numeerisesti funktio-olio.
4    * @author Vesa Lappalainen
5    * @version 1.0, 25.03.2003
6    */
7   public class Integroi3 {
8   
9     interface FunktioRR {
10      public double f(double x);
11      public String toString();
12      public double intfun(double x);
13      public double derfun(double x);
14      public double defint(double x1, double x2);
15    }
16  
17    public static class PerusFunktio implements FunktioRR {
18      public double f(double x) { return 0; }
19      public String toString()  { return ""; }
20      public double intfun(double x) { return 0; }
21      public double derfun(double x) { return 0; }
22      public double defint(double x1, double x2) { return 0; }
23    }
24  
25    static class SinFun extends PerusFunktio {
26      public double f(double x) { return Math.sin(x); }
27    }
28  
29    static class ExpFun extends PerusFunktio {
30      public double f(double x) { return Math.exp(x); }
31    }
32  
33    static class OmaFun extends PerusFunktio  {
34      public double f(double x) { return 2*x- 5;      }
35    }
36  
37    public static double integroi(FunktioRR f, double x1, double x2, int tiheys) {
38      double x,dx,summa=0;
39  
40      dx = (x2- x1)/tiheys;
41  
42      for (x=x1+dx/2 ; x<x2; x+=dx)
43        summa += f.f(x)*dx;
44  
45      return summa;
46    }
47  
48  
49    public static void main(String[] args)  {
50      double ifx;
51      ifx = integroi(new OmaFun(),0,5,100);
52      System.out.println("Integraali omafun(x) väliltä [0,5] on noin "+
53                         Mjonot.fmt(ifx,7,5));
54      ifx = integroi(new SinFun(),0,Math.PI,1000);
55      System.out.println("Integraali sin(x) väliltä [0,pi] on noin "+
56                         Mjonot.fmt(ifx,7,5));
57      ifx = integroi(new ExpFun(),0,1,500);
58      System.out.println("Integraali exp(x) väliltä [0,1] on noin "+
59                         Mjonot.fmt(ifx,7,5));
60    }
61  }
62