Skip to content

Instantly share code, notes, and snippets.

@hiiwave
Last active July 24, 2018 02:15
Show Gist options
  • Save hiiwave/7e7db0f4458c2da7a8735f440a182a41 to your computer and use it in GitHub Desktop.
Save hiiwave/7e7db0f4458c2da7a8735f440a182a41 to your computer and use it in GitHub Desktop.
Find root by Newton method
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef double (*func)(double);
double f(double x) {
return x * x - 2.0 * x - 5.0;
}
double fd(double x) {
return 2.0 * x - 2.0;
}
/**
* find the x-intercept of a line given a point and slope
*/
double getIntercept(double x0, double y0, double m) {
return x0 - y0 / m;
}
/*
* return the estimated root, modify *iter by iteration count
*/
double newton(double x0, func f, func fd, double eps, double maxiter, int* iter) {
for (*iter = 0; *iter < maxiter; ++*iter) {
double y0 = f(x0);
if (fabs(y0) < eps) return x0;
x0 = getIntercept(x0, y0, fd(x0));
}
printf("max-iter reached");
return x0;
}
int main() {
double root;
int* iter_count = (int *)malloc(sizeof(*iter_count));
root = newton(5, f, fd, 0.001, 100, iter_count);
printf("Case 1: root = %lf, iter_count = %d\n", root, *iter_count);
root = newton(-3, f, fd, 0.001, 100, iter_count);
printf("Case 2: root = %lf, iter_count = %d\n", root, *iter_count);
free(iter_count);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment