Advertisement
Guest User

Root Find Method (Error)

a guest
May 14th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.54 KB | None | 0 0
  1. using System;
  2. using MathNet.Numerics;
  3. using MathNet.Numerics.RootFinding;
  4. using MathNet.Symbolics;
  5. using static System.Collections.Specialized.BitVector32;
  6. using Expr = MathNet.Symbolics.SymbolicExpression;
  7.  
  8. namespace RootFindingMethods
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. try
  15. {
  16. string functionString = ReadFunctionFromUser();
  17. double a = ReadDoubleFromUser("Enter the left endpoint a: ");
  18. double b = ReadDoubleFromUser("Enter the right endpoint b: ");
  19. double tolerance = ReadDoubleFromUser("Enter the tolerance TOL: ");
  20. int maxIterations = ReadIntFromUser("Enter the maximum iterations NMAX: ");
  21.  
  22. var expression = Expr.Parse(functionString);
  23. var function = expression.Compile("x");
  24.  
  25. Func<double, double> f = x => function(x);
  26.  
  27. // Compute the derivative of the function
  28. var derivativeExpression = Expr.Differentiate(expression, "x");
  29. var derivativeFunction = derivativeExpression.Compile("x");
  30. Func<double, double> df = x => derivativeFunction(x);
  31.  
  32. Console.WriteLine("Choose a method:");
  33. Console.WriteLine("1. Bisection");
  34. Console.WriteLine("2. Newton-Raphson");
  35. int methodChoice = ReadIntFromUser("Enter your choice (1 or 2): ");
  36.  
  37. double root;
  38. int iterations;
  39.  
  40. switch (methodChoice)
  41. {
  42. case 1: // Bisection method
  43. (root, iterations) = BisectionMethod(f, a, b, tolerance, maxIterations);
  44. break;
  45. case 2: // Newton-Raphson method
  46. double initialGuess = ReadDoubleFromUser("Enter the initial guess: ");
  47. (root, iterations) = NewtonRaphsonMethod(f, df, initialGuess, tolerance, maxIterations);
  48. break;
  49. default:
  50. throw new ArgumentException("Invalid method choice.");
  51. }
  52.  
  53. if (double.IsNaN(root))
  54. {
  55. Console.WriteLine("Method failed.");
  56. }
  57. else
  58. {
  59. Console.WriteLine("The root is approximately " + root);
  60. Console.WriteLine("Number of iterations: " + iterations);
  61. }
  62. }
  63. catch (MathNet.Numerics.NonConvergenceException ex)
  64. {
  65. Console.WriteLine(ex.Message);
  66. }
  67. catch (Exception ex)
  68. {
  69. Console.WriteLine("Error: " + ex.Message);
  70. }
  71. }
  72.  
  73. private static (double, int) BisectionMethod(Func<double, double> f, double a, double b, double tolerance, int maxIterations)
  74. {
  75. int iterations = 0; // Initialize the iteration count
  76. double root = Bisection.FindRoot(f, a, b, tolerance);
  77.  
  78. while (iterations < maxIterations)
  79. {
  80. // Calculate midpoint
  81. double c = (a + b) / 2;
  82.  
  83. // Check if root is found within tolerance
  84. if (Math.Abs(f(c)) < tolerance)
  85. {
  86. root = c;
  87. break;
  88. }
  89.  
  90. // Update interval
  91. if (f(a) * f(c) < 0)
  92. b = c;
  93. else
  94. a = c;
  95.  
  96. iterations++;
  97. }
  98.  
  99. return (root, iterations);
  100. }
  101.  
  102. private static (double, int) NewtonRaphsonMethod(Func<double, double> f, Func<double, double> df, double initialGuess, double tolerance, int maxIterations)
  103. {
  104. int iterations = 0; // Initialize the iteration count
  105. double root = initialGuess;
  106.  
  107. while (iterations < maxIterations)
  108. {
  109. double fValue = f(root);
  110. double dfValue = df(root);
  111.  
  112. // Update root using Newton-Raphson formula
  113. root = root - fValue / dfValue;
  114.  
  115. // Check if root is found within tolerance
  116. if (Math.Abs(f(root)) < tolerance)
  117. {
  118. break;
  119. }
  120.  
  121. iterations++;
  122. }
  123.  
  124. return (root, iterations);
  125. }
  126.  
  127. private static string ReadFunctionFromUser()
  128. {
  129. Console.Write("Enter the function f(x): ");
  130. string functionString = Console.ReadLine();
  131. if (string.IsNullOrEmpty(functionString))
  132. {
  133. throw new ArgumentException("Function string cannot be null or empty.");
  134. }
  135. return functionString;
  136. }
  137.  
  138. private static double ReadDoubleFromUser(string prompt)
  139. {
  140. Console.Write(prompt);
  141. if (!double.TryParse(Console.ReadLine(), out double value))
  142. {
  143. throw new FormatException("Invalid input. Please enter a valid number.");
  144. }
  145. return value;
  146. }
  147.  
  148. private static int ReadIntFromUser(string prompt)
  149. {
  150. Console.Write(prompt);
  151. if (!int.TryParse(Console.ReadLine(), out int value))
  152. {
  153. throw new FormatException("Invalid input. Please enter a valid integer.");
  154. }
  155. return value;
  156. }
  157. }
  158. }
  159.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement