Newton's Method in C#

 1     public static class BondInterestMath
 2     {
 3         public delegate double Function(double x);
 4 
 5         //F(x) = cos(x)-3*pow(x,3) = 0
 6         public static double Func(double x)
 7         {
 8             return Math.Cos(x) - 3 * Math.Pow(x, 3);
 9         }
10 
11         public static double Derivative(double x)
12         {
13             return -Math.Sin(x) - 9 * Math.Pow(x, 2);
14         }
15 
16         public static double NewtonMethod(Function func, Function derivative, double x0, double epsilon)
17         {
18             //Max interation number 10000 by default
19             int MaxTimes = 10000;
20             double guess = x0;
21             double result = x0;
22             for (int i = 1; i <= MaxTimes; i++)
23             {
24                 guess = result;
25                 result = guess - func(guess) / derivative(guess);
26                 if (Math.Abs(result - guess) < epsilon || Math.Abs(func(result)) < epsilon)
27                 {
28                     Console.WriteLine("iteration = {0}", i);
29                     break;
30                 }
31             }
32             return result;
33         }
34     }
原文地址:https://www.cnblogs.com/feishunji/p/1906099.html