Newton's method
unknown
c_cpp
a year ago
1.3 kB
4
Indexable
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int N; double f(double x) { // define the function return log(x) + sin(pow(x, 2)); // replace with your function } double derf(double x) { // define the derivative of the function return 1/x + cos(pow(x, 2))*2*x; // replace with derivative of your function } double newtonsMethod(double x0, double eps) { // newtons method function int i = 0; double x1; while (1) { x1 = x0 - (f(x0) / derf(x0)); if (fabs(x1 - x0) <= eps) { break; } x0 = x1; i++; if (i==N) { break; } } return x1; } int main() { printf("Enter the threshold number of iterations: "); scanf("%d", &N); double xbeg; // reference point printf("Enter a reference point: "); scanf("%lf", &xbeg); double x0 = xbeg; // assigning a value to a variable from a function int nod; // number of decimal places printf("Enter a number of decimal places: "); scanf("%d", &nod); double eps = 1 / pow(10, (double)nod); // tolerance double root = newtonsMethod(x0, eps); // finding root printf("\nThe root is: %.*f\n", nod, root); // printing return 0; }
Editor is loading...
Leave a Comment