Guest User

Untitled

a guest
May 26th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. interface function {
  2.     double calc(double x);
  3. }
  4.  
  5. class atanderivate implements function {
  6.     public double calc(double x) {
  7.         return 1.0 / (1.0 + x * x);
  8.     }
  9.  
  10.     public String toString() {
  11.         return "1/(1+x^2)";
  12.     }
  13. }
  14.  
  15. class quartercircle implements function {
  16.     public double calc(double x) {
  17.         return Math.sqrt(1-x*x);
  18.     }
  19.  
  20.     public String toString() {
  21.         return "sqrt(1-x^2)";
  22.     }
  23. }
  24.  
  25. public class Integrate {
  26.     static double integrate(double a, double b, int n, function f) {
  27.         double h = (b-a)/n;
  28.         if(h<=1.0E-8){
  29.             //wenn die Schrittweite h kleiner ist auf 10^-8, so ändere ich h in 10^-8 und n muss dementsprechend auch verändert werden
  30.             h = 1.0E-8;
  31.             n = (int)((b-a)/h);
  32.         }
  33.         double ausgabe = h * ((f.calc(a) + f.calc(b))/2 + summe(a, n, h, f));   //Formel aus der Mittschrift. summe(...) beschreibt eine normale Summe, die ich extra in eine andere Methode ausgelagert habe.
  34.         return ausgabe;
  35.     }
  36.    
  37.     public static double summe(double a, int n, double h, function f){
  38.         double ausgabe = 0.0;
  39.         for(int i = 1; i<n; i++){
  40.             //die Summe fängt bei 1 an und geht bis n-1. Es wird immer der Funktionswert an der stelle (a + h*i) aufaddiert
  41.             double xi = a + h*i;
  42.             ausgabe += f.calc(xi);
  43.         }
  44.         return ausgabe;
  45.     }
  46.  
  47.     public static void main(String[] args) {
  48.         int n = 1000000000;
  49.  
  50.         function f = new atanderivate();
  51.         double integral = integrate(0.0, 1.0, n, f);
  52.         System.out.println("Integral von " + f + " von 0.0 bis 1.0 (" + n + " Schritte) = " + integral + " => PI = " + (4.0 * integral) + " Fehler: " + (Math.PI - 4.0 * integral));
  53.  
  54.         f = new quartercircle();
  55.         integral = integrate(0.0, 1.0, n, f);
  56.         System.out.println("Integral von " + f + " von 0.0 bis 1.0 (" + n + " Schritte) = " + integral + " => PI = " + (4.0 * integral) + " Fehler: " + (Math.PI - 4.0 * integral));
  57.        
  58.         /*
  59.          * Die erste Funktion (1/(1+x^2)) hat bei allen von mir ausprobierten n bessere Werte erziehlt als der Viertelkreis (Wurzel aus (1-x^2))
  60.          */
  61.     }
  62. }
Add Comment
Please, Sign In to add comment