Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface function {
- double calc(double x);
- }
- class atanderivate implements function {
- public double calc(double x) {
- return 1.0 / (1.0 + x * x);
- }
- public String toString() {
- return "1/(1+x^2)";
- }
- }
- class quartercircle implements function {
- public double calc(double x) {
- return Math.sqrt(1-x*x);
- }
- public String toString() {
- return "sqrt(1-x^2)";
- }
- }
- public class Integrate {
- static double integrate(double a, double b, int n, function f) {
- double h = (b-a)/n;
- if(h<=1.0E-8){
- //wenn die Schrittweite h kleiner ist auf 10^-8, so ändere ich h in 10^-8 und n muss dementsprechend auch verändert werden
- h = 1.0E-8;
- n = (int)((b-a)/h);
- }
- 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.
- return ausgabe;
- }
- public static double summe(double a, int n, double h, function f){
- double ausgabe = 0.0;
- for(int i = 1; i<n; i++){
- //die Summe fängt bei 1 an und geht bis n-1. Es wird immer der Funktionswert an der stelle (a + h*i) aufaddiert
- double xi = a + h*i;
- ausgabe += f.calc(xi);
- }
- return ausgabe;
- }
- public static void main(String[] args) {
- int n = 1000000000;
- function f = new atanderivate();
- double integral = integrate(0.0, 1.0, n, f);
- 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));
- f = new quartercircle();
- integral = integrate(0.0, 1.0, n, f);
- 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));
- /*
- * 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))
- */
- }
- }
Add Comment
Please, Sign In to add comment