Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1.  
  2. public class MullerMethod {
  3.    
  4.     private static final double epsilon = 1 * Math.pow(10, -8);
  5.  
  6.     private static double f(double x) {
  7.    
  8.         return Math.log(x) + x;
  9.     }
  10.    
  11.     public static void main(String args[]) {
  12.        
  13.         double x_0 = 3;
  14.         double x_1 = 2;
  15.         double x_2 = 1;
  16.        
  17.         double k_0, k_1;
  18.         double h_0, h_1;
  19.        
  20.         double A, B, C;
  21.        
  22.         double rootEstimation = 0.0;
  23.        
  24.         int iteration = 0;
  25.         while (Math.abs(x_0 - x_1) >= epsilon) {
  26.            
  27.             // Calculate k_0, k_1, h_0, and h_1
  28.             k_0 = f(x_0) - f(x_2);
  29.             k_1 = f(x_1) - f(x_2);
  30.             h_0 = x_0 - x_2;
  31.             h_1 = x_1 - x_2;
  32.            
  33.             // Calculating the coefficients
  34.             A = (h_1 * k_0 - h_0 * k_1) / (Math.pow(h_0, 2) * h_1 - Math.pow(h_1, 2) * h_0);
  35.             B = (k_0 - A * Math.pow(h_0, 2)) / (h_0);
  36.             C = f(x_2);
  37.            
  38.             double sign = (B < 0) ? -1 : 1;
  39.            
  40.             // Plug in to the alternate version of the quadratic formula
  41.             rootEstimation = x_2 - (2 * C) / (B + sign * Math.sqrt(Math.pow(B, 2) - 4 * A * C));
  42.             x_0 = x_1;
  43.             x_1 = x_2;
  44.             x_2 = rootEstimation;
  45.            
  46.             iteration++;
  47.             System.out.println("Iteration " + iteration + ": " + "A: " + A + "  B: " + B + "  C: " + C + "  Root estimation: " + rootEstimation);
  48.         }
  49.        
  50.         System.out.println("After " + iteration + " iterations, the estimated root was: " + rootEstimation + ".");
  51.        
  52.     }
  53.    
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement