Advertisement
Guest User

Untitled

a guest
Nov 11th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. // Java Program to find root of a function, f(x)
  2. import java.io.*;
  3. import static java.lang.Math.*;
  4.  
  5. class Muller
  6. {
  7.     static final int MAX_ITERATIONS = 10000;
  8.  
  9.     // function to calculate f(x)
  10.     static double f(double x)
  11.     {
  12.         // Taking f(x) = x ^ 3 + 2x ^ 2 + 10x - 20
  13.         return 1*pow(x, 3) + 2*x*x + 10*x - 20;
  14.     }
  15.  
  16.     static void Muller(double a, double b, double c)
  17.     {
  18.         int i;
  19.         double res;
  20.  
  21.         for (i = 0;; ++i)
  22.         {
  23.             // Calculating various constants required
  24.             // to calculate x3
  25.             double f1 = f(a);
  26.             double f2 = f(b);
  27.             double f3 = f(c);
  28.             double d1 = f1 - f3;
  29.             double d2 = f2 - f3;
  30.             double h1 = a - c;
  31.             double h2 = b - c;
  32.             double a0 = f3;
  33.             double a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2)))
  34.                         / ((h1*h2) * (h1-h2)));
  35.             double a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2)));
  36.             double x = ((-2*a0)/(a1 + abs(sqrt(a1*a1-4*a0*a2))));
  37.             double y = ((-2*a0)/(a1-abs(sqrt(a1*a1-4*a0*a2))));
  38.  
  39.             // Taking the root which is closer to x2
  40.             if (x >= y)
  41.                 res = x + c;
  42.             else
  43.                 res = y + c;
  44.  
  45.             // checking for resemblance of x3 with x2 till
  46.             // two decimal places
  47.             double m = res*100;
  48.             double n = c*100;
  49.             m = floor(m);
  50.             n = floor(n);
  51.             if (m == n)
  52.                 break;
  53.             a = b;
  54.             b = c;
  55.             c = res;
  56.             if (i > MAX_ITERATIONS)
  57.             {
  58.                 System.out.println("Root cannot be found using" +
  59.                                 " Muller's method");
  60.                 break;
  61.             }
  62.         }
  63.         if (i <= MAX_ITERATIONS)
  64.             System.out.println("The value of the root is " + res);
  65.     }
  66.  
  67.     // Driver main function
  68.     public static void main(String args[])
  69.     {
  70.         double a = 0, b = 1, c = 2;
  71.         Muller(a, b, c);
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement