Skip to content

Instantly share code, notes, and snippets.

@Colk-tech
Last active October 13, 2023 03:07
Show Gist options
  • Save Colk-tech/8b5943a3eb857a1c62f231b59cf5adad to your computer and use it in GitHub Desktop.
Save Colk-tech/8b5943a3eb857a1c62f231b59cf5adad to your computer and use it in GitHub Desktop.
Newton's method for equations
#include <stdio.h>
#include <math.h>
#define MAX 20
int main(void) {
int i;
double x0, x1, fx0, dfx0, eps = 0.0001;
printf("x0 = ");
scanf("%lf", &x0);
for (i = 1; i <= MAX; i++) {
fx0 = x0 * x0 - 2 * x0 - 1;
dfx0 = 2 * x0 - 2;
x1 = x0 - fx0 / dfx0;
if (fabs(x1 - x0) < eps) {
break;
} else {
x0 = x1;
}
printf("x%d = %lf\n", i, x1);
}
printf("x1 = %lf\n", x1);
printf("f(x1) = %lf\n", x1 * x1 - 2 * x1 - 1);
printf("i = %d\n", i);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment