-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewtons_method.c
More file actions
98 lines (83 loc) · 2.68 KB
/
newtons_method.c
File metadata and controls
98 lines (83 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* newtons_method.c
*
* This program demonstrates Newton's method for finding the
* root of a single-variable function f(x).
*
* Example function:
* f(x) = x^3 - x - 1
*
* Derivative:
* f'(x) = 3x^2 - 1
*
* The root is approximately 1.3247.
*
* Note: This algorithm is sequential by nature. The (n+1)th
* iteration depends directly on the result of the nth iteration,
* so parallelization of the main loop is not possible.
*/
#include <stdio.h>
#include <math.h>
// Define the function f(x)
double f(double x) {
return x * x * x - x - 1.0;
}
// Define the derivative f'(x)
double f_prime(double x) {
return 3.0 * x * x - 1.0;
}
/**
* @brief Performs Newton's method to find a root.
*
* @param x0 Initial guess.
* @param tolerance Convergence tolerance.
* @param max_iterations Maximum number of iterations.
*/
void newtons_method(double x0, double tolerance, int max_iterations) {
double x_old = x0;
double x_new;
double f_x;
double f_prime_x;
double step;
int iteration = 0;
printf("Starting Newton's method with x0 = %.6f\n", x0);
printf("---------------------------------------------\n");
printf("Iter | x_n | f(x_n) | f'(x_n) | Step Size\n");
printf("---------------------------------------------\n");
while (iteration < max_iterations) {
f_x = f(x_old);
f_prime_x = f_prime(x_old);
// Check for division by zero (tangent is horizontal)
if (fabs(f_prime_x) < 1e-12) {
printf("Error: Derivative is zero at x = %.6f\n", x_old);
return;
}
// Newton's iteration formula
step = f_x / f_prime_x;
x_new = x_old - step;
printf("%4d | %.6f | %.6e | %.6e | %.6e\n",
iteration, x_old, f_x, f_prime_x, fabs(step));
// Check for convergence
// We check if the step size is small OR if f(x) is close to zero
if (fabs(step) < tolerance || fabs(f(x_new)) < tolerance) {
printf("---------------------------------------------\n");
printf("Convergence reached in %d iterations.\n", iteration + 1);
printf("Root is approximately: %.8f\n", x_new);
return;
}
// Prepare for next iteration
x_old = x_new;
iteration++;
}
printf("---------------------------------------------\n");
printf("Failed to converge in %d iterations.\n", max_iterations);
printf("Current value: %.8f\n", x_new);
}
int main() {
// Set initial parameters
double initial_guess = 1.5; // A good starting guess
double tolerance = 1e-7;
int max_iterations = 100;
newtons_method(initial_guess, tolerance, max_iterations);
return 0;
}