Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApplication1
  8. {
  9. class Program
  10. {
  11.  
  12. public static double f(double x)
  13. {
  14. return Math.Exp(5 * x) - Math.Cos(3 * x) - 5 * x - 2;
  15. }
  16.  
  17.  
  18. public static double newton(double a, double b, double error) {
  19.  
  20. if (f(a) == 0) return a;
  21. if (f(b) == 0) return b;
  22. double x1;
  23. if (f(a) * fDerivative2(a) > 0) x1 = a;
  24. else
  25. if (f(b) * fDerivative2(b) > 0) x1 = b;
  26. else
  27.  
  28. {
  29. Console.WriteLine("The method cannot be used");
  30. return 0;
  31.  
  32. }
  33. double x0;
  34. do
  35. {
  36. x0 = x1;
  37. x1 = x0 - f(x0) / fDerivative(x0);
  38.  
  39.  
  40. } while (Math.Abs(x1 - x0) * Math.Abs(x1 - x0) > error);
  41.  
  42. return x1;
  43.  
  44. }
  45.  
  46. public static double fDerivative(double x) {
  47.  
  48. double h = 1;
  49. double fm1 = (f(x + h) - f(x)) / h;
  50. h *= 0.1;
  51. double f0 = (f(x + h) - f(x)) / h;
  52. double dist = Math.Abs(fm1 - f0), oldDist;
  53.  
  54. do
  55. {
  56. oldDist = dist;
  57. h *= 0.1;
  58. fm1 = f0;
  59. f0 = (f(x + h) - f(x)) / h;
  60. dist = Math.Abs(fm1 - f0);
  61.  
  62. } while (Math.Abs(oldDist) > Math.Abs(dist));
  63.  
  64.  
  65. return fm1;
  66. }
  67.  
  68. public static double fDerivative2(double x)
  69. {
  70.  
  71. double h = 1;
  72. double fm1 = (fDerivative(x + h) - fDerivative(x)) / h;
  73. h *= 0.1;
  74. double f0 = (fDerivative(x + h) - fDerivative(x)) / h;
  75. double dist = Math.Abs(fm1 - f0), oldDist;
  76.  
  77. do
  78. {
  79. oldDist = dist;
  80. h *= 0.1;
  81. fm1 = f0;
  82. f0 = (fDerivative(x + h) - fDerivative(x)) / h;
  83. dist = Math.Abs(fm1 - f0);
  84.  
  85. } while (Math.Abs(oldDist) > Math.Abs(dist));
  86.  
  87.  
  88. return fm1;
  89. }
  90.  
  91.  
  92. static void Main(string[] args)
  93. {
  94. Console.WriteLine(newton(0,1,0.000000001));
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102. }
  103. }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement