Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication1
- {
- class Program
- {
- public static double f(double x)
- {
- return Math.Exp(5 * x) - Math.Cos(3 * x) - 5 * x - 2;
- }
- public static double newton(double a, double b, double error) {
- if (f(a) == 0) return a;
- if (f(b) == 0) return b;
- double x1;
- if (f(a) * fDerivative2(a) > 0) x1 = a;
- else
- if (f(b) * fDerivative2(b) > 0) x1 = b;
- else
- {
- Console.WriteLine("The method cannot be used");
- return 0;
- }
- double x0;
- do
- {
- x0 = x1;
- x1 = x0 - f(x0) / fDerivative(x0);
- } while (Math.Abs(x1 - x0) * Math.Abs(x1 - x0) > error);
- return x1;
- }
- public static double fDerivative(double x) {
- double h = 1;
- double fm1 = (f(x + h) - f(x)) / h;
- h *= 0.1;
- double f0 = (f(x + h) - f(x)) / h;
- double dist = Math.Abs(fm1 - f0), oldDist;
- do
- {
- oldDist = dist;
- h *= 0.1;
- fm1 = f0;
- f0 = (f(x + h) - f(x)) / h;
- dist = Math.Abs(fm1 - f0);
- } while (Math.Abs(oldDist) > Math.Abs(dist));
- return fm1;
- }
- public static double fDerivative2(double x)
- {
- double h = 1;
- double fm1 = (fDerivative(x + h) - fDerivative(x)) / h;
- h *= 0.1;
- double f0 = (fDerivative(x + h) - fDerivative(x)) / h;
- double dist = Math.Abs(fm1 - f0), oldDist;
- do
- {
- oldDist = dist;
- h *= 0.1;
- fm1 = f0;
- f0 = (fDerivative(x + h) - fDerivative(x)) / h;
- dist = Math.Abs(fm1 - f0);
- } while (Math.Abs(oldDist) > Math.Abs(dist));
- return fm1;
- }
- static void Main(string[] args)
- {
- Console.WriteLine(newton(0,1,0.000000001));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement