Advertisement
daniv1

newton

Feb 20th, 2019
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Newton
  4. {  
  5.     class Program
  6.     {
  7.         static double EPSILON = 0.00001;
  8.  
  9.         static double func(double x)
  10.         {
  11.             return x *x - 4;
  12.         }
  13.         public static void Swap<T>(ref T a, ref T b)
  14.         {
  15.             T c = a;
  16.             a = b;
  17.             b = c;
  18.         }
  19.  
  20.         static double deriveredFunc(double x)
  21.         {
  22.             double d = EPSILON / 100;
  23.             return (func(x + d) - func(x)) / d;
  24.         }
  25.         static double f2p(double x)
  26.         {
  27.             double d = EPSILON / 100.0;
  28.             return ((func(x + d) + func(x - d) - 2 * func(x)) / (d*d));
  29.         }
  30.        
  31.         static void newtonRaphson(double a,double b)
  32.         {
  33.             double x = b;
  34.             if (func(x) * f2p(x) < 0.0)
  35.             {
  36.                 x = a;
  37.             }
  38.             int cnt = 0;
  39.                 double h = func(x) / deriveredFunc(x);
  40.                 while (Math.Abs(h) >= EPSILON)
  41.                 {
  42.                 cnt++;
  43.                     h = func(x) / deriveredFunc(x);
  44.  
  45.                     x = x - h;
  46.                 }
  47.  
  48.                 Console.WriteLine("The value of the"
  49.                             + " root is : "
  50.                             + Math.Round(x * 100.0) / 100.0);
  51.             Console.WriteLine("cnt = " + cnt);
  52.  
  53.            
  54.         }
  55.  
  56.         // Driver code
  57.         public static void Main()
  58.         {
  59.  
  60.             // Initial values assumed
  61.             Console.WriteLine("Input a");
  62.             double a = Convert.ToDouble(Console.ReadLine());
  63.             Console.WriteLine("Input b");
  64.             double b = Convert.ToDouble(Console.ReadLine());
  65.             if (a > b)
  66.             {
  67.                 Program.Swap(ref a, ref b);
  68.             }
  69.             newtonRaphson(a,b);
  70.             Console.ReadLine();
  71.         }
  72.     }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement