Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
newton_raphson_root.c File Reference

Find approximate solution for \(f(x) = 0\) using Newton-Raphson interpolation algorithm. More...

#include <complex.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for newton_raphson_root.c:

Macros

#define ACCURACY   1e-10
 solution accuracy
 

Functions

double complex func (double complex x)
 Return value of the function to find the root for.
 
double complex d_func (double complex x)
 Return first order derivative of the function.
 
int main (int argc, char **argv)
 main function
 

Detailed Description

Find approximate solution for \(f(x) = 0\) using Newton-Raphson interpolation algorithm.

Author
Krishna Vedala

Function Documentation

◆ d_func()

double complex d_func ( double complex  x)

Return first order derivative of the function.

\(f'(x)\)

32{ return 2. * x; }

◆ func()

double complex func ( double complex  x)

Return value of the function to find the root for.

\(f(x)\)

23{
24 return x * x - 3.; /* x^2 = 3 - solution is sqrt(3) */
25 // return x * x - 2.; /* x^2 = 2 - solution is sqrt(2) */
26}

◆ main()

int main ( int  argc,
char **  argv 
)

main function

38{
39 double delta = 1;
40 double complex cdelta = 1;
41
42 /* initialize random seed: */
43 srand(time(NULL));
44
45 /* random initial approximation */
46 double complex root = (rand() % 100 - 50) + (rand() % 100 - 50) * I;
47
48 unsigned long counter = 0;
49 /* iterate till a convergence is reached */
50 while (delta > ACCURACY && counter < ULONG_MAX)
51 {
52 cdelta = func(root) / d_func(root);
53 root += -cdelta;
54 counter++;
55 delta = fabs(cabs(cdelta));
56
57#if defined(DEBUG) || !defined(NDEBUG)
58 if (counter % 50 == 0)
59 {
60 double r = creal(root);
61 double c = cimag(root);
62
63 printf("Iter %5lu: Root: %4.4g%c%4.4gi\t\tdelta: %.4g\n", counter,
64 r, c >= 0 ? '+' : '-', c >= 0 ? c : -c, delta);
65 }
66#endif
67 }
68
69 double r = creal(root);
70 double c = fabs(cimag(root)) < ACCURACY ? 0 : cimag(root);
71
72 printf("Iter %5lu: Root: %4.4g%c%4.4gi\t\tdelta: %.4g\n", counter, r,
73 c >= 0 ? '+' : '-', c >= 0 ? c : -c, delta);
74
75 return 0;
76}
double complex func(double complex x)
Return value of the function to find the root for.
Definition newton_raphson_root.c:22
double complex d_func(double complex x)
Return first order derivative of the function.
Definition newton_raphson_root.c:32
#define ACCURACY
solution accuracy
Definition newton_raphson_root.c:16
Here is the call graph for this function: