Advertisement
goodvibes2298

Simpsons 3/8th rule

Feb 27th, 2023 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1.     static double mathFunc(double x) {
  2.         // function = e^x + x^3
  3.         return Math.pow(Math.E, x)+Math.pow(x, 3);
  4.     }
  5.    
  6.     // Simpsons 3/8th rule
  7.     // a is begging of interval b is the end
  8.     // n is the amount of times we are splitting
  9.     //that function into smaller segments that are gonna be added together
  10.     static double simpsons38th(double a, double b, double n) {
  11.         double result = 0;
  12.         double h = (b-a)/n;
  13.         result += (mathFunc(a)+mathFunc(b));
  14.        
  15.         for(int i = 0; i < n ; i++) {
  16.             double x;
  17.             if(i%3 != 0) {
  18.                 x = (a + i * h);
  19.                 result +=  3.0 * mathFunc(x);
  20.                 //System.out.println(i);
  21.             }  
  22.         }
  23.        
  24.         for(int i = 0; i < n/3  ; i++) {
  25.             double x = (a + i * h * 3);
  26.             result +=  2.0 * mathFunc(x);
  27.             //System.out.println(i*3);
  28.         }
  29.        
  30.         return (3.0 * h * result) / 8.0 ;
  31.     }
  32.  
  33.     public static void main(String[] args) {
  34.         System.out.println("f(x) = e^x + x^3");
  35.         double a = 0, b = 1;
  36.         int n = 10000;
  37.         System.out.println("Simpson 3/8th    = " + simpsons38th(a, b, n));
  38.     }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement