I tried to implement Newton's method in C language

What is Newton's method?

The Newton method is omitted here. http://qiita.com/PlanetMeron/items/09d7eb204868e1a49f49 This person's article may be easy to understand

differential

Differentiate according to the definition of the derivative.

#define DX 0.00000001

double f(double x) {
    return - 2*pow(x,4) + 3*pow(x,3) + 4*x - 3;
}

//Find the derivative
double fd(double x) {
    return (f(x+DX) - f(x)) / DX;
}

For dx, enter an appropriate value close to 0. f is the return value for x, and fd finds its derivative.

Find the tangent

With df as the slope

y = df(currentX) * (x - currentX) + f(currentX)

currentX is the x coordinate of the position where you want to find the tangent

Find the x-intercept

//Returns x intercept, y=ax+shape of b, ax+b=When 0
double searchInterceptX(double a, double b) {
    return -b/a;
}

The intercept of y = ax + b is easy to stop!

Completed file

Newton.c


#include <stdio.h>
#include <math.h>

#define DX 0.00000001

//Function entered
double f1(double x) {
    return - 2*pow(x,4) + 3*pow(x,3) + 4*x - 3;
}
double f2(double x) {
    return -2 * sin(x) + exp(x+1) + x - 10;
}

//Find the derivative
double fd(double (*func)(double), double x) {
    return (func(x+DX) - func(x)) / DX;
}

//Returns x intercept, y=ax+shape of b, ax+b=When 0
double searchInterceptX(double a, double b) {
    return -b/a;
}

//Find the next X by Newton's method
double nextX(double (*func)(double), double currentX) {
    double dif = fd(func, currentX);
    return searchInterceptX(dif, func(currentX) - dif*currentX);
}

//Solve and return the result
//You really should evaluate the error
double solve(double (*func)(double), double initialX) {
    double currentX = initialX;
    for(int i=0; i<10; i++) {
        printf("%lf\n", currentX);
        currentX = nextX(f1, currentX);
    }
    return currentX;
}

int main() {
    printf("f1\n");
    printf("result = %lf\n", solve(f1, 1));

    printf("\n");

    printf("f2\n");
    printf("result = %lf\n", solve(f2, M_PI));
}

I implemented it using a function pointer. The second argument of the solve function is the initial x coordinate of Newton's method. Keep the value close to the solution you want to find.

Error evaluation should be done, but this time only the number of loops

Recommended Posts