001 import fi.jyu.mit.ohj2.*;
002 /**
003 * Ohjelmalla integroidaan numeerisesti funktio-olio.
004 * @author Vesa Lappalainen
005 * @version 1.0, 25.03.2003
006 */
007 public class Integroi2 {
008
009 interface FunktioRR {
010 public double f(double x);
011 }
012
013 static class SinFun implements FunktioRR {
014 public double f(double x) { return Math.sin(x); }
015 }
016
017 static class ExpFun implements FunktioRR {
018 public double f(double x) { return Math.exp(x); }
019 }
020
021 static class OmaFun implements FunktioRR {
022 public double f(double x) { return 2*x- 5; }
023 }
024
025 public static double integroi(FunktioRR f, double x1, double x2, int tiheys) {
026 double x,dx,summa=0;
027
028 dx = (x2- x1)/tiheys;
029
030 for (x=x1+dx/2 ; x<x2; x+=dx)
031 summa += f.f(x)*dx;
032
033 return summa;
034 }
035
036
037 public static void main(String[] args) {
038 double ifx;
039 ifx = integroi(new OmaFun(),0,5,100);
040 System.out.println("Integraali omafun(x) väliltä [0,5] on noin "+
041 Mjonot.fmt(ifx,7,5));
042 ifx = integroi(new SinFun(),0,Math.PI,1000);
043 System.out.println("Integraali sin(x) väliltä [0,pi] on noin "+
044 Mjonot.fmt(ifx,7,5));
045 ifx = integroi(new ExpFun(),0,1,500);
046 System.out.println("Integraali exp(x) väliltä [0,1] on noin "+
047 Mjonot.fmt(ifx,7,5));
048 }
049 }