fork(1) download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define EPSILON 1e-10
  5. #define MAX_ITER 100
  6.  
  7. #define ROOT_TOL 1e-4 // tolerance for treating roots as identical
  8.  
  9. double f(double x) {
  10. return (((x*x*x*x) + x*x*x) - 54.0*x*x - 224.0*x - 345.0);
  11. }
  12.  
  13. double df(double x) {
  14. return (4.0*x*x*x + 3.0*x*x - 108.0*x - 224.0);
  15. }
  16.  
  17. double newton(double x0) {
  18. double x = x0;
  19.  
  20. for (int i = 0; i < MAX_ITER; i++) {
  21. double fx = f(x);
  22. double dfx = df(x);
  23.  
  24. if (fabs(dfx) < 1e-12) break;
  25.  
  26. double dx = fx / dfx;
  27. x -= dx;
  28.  
  29. if (fabs(dx) < EPSILON) return x;
  30. }
  31.  
  32. return x;
  33. }
  34.  
  35. int is_duplicate(double x, double roots[], int count) {
  36. for (int i = 0; i < count; i++) {
  37. if (fabs(x - roots[i]) < ROOT_TOL) return 1;
  38. }
  39. return 0;
  40. }
  41.  
  42. int main() {
  43. double guesses[] = {10.0, 2.0, -4.5, -6.0};
  44. double roots[4];
  45. int found = 0;
  46.  
  47. printf("=== Newton-Raphson roots (deduplicated) ===\n");
  48.  
  49. for (int i = 0; i < 4; i++) {
  50. double r = newton(guesses[i]);
  51.  
  52. if (!is_duplicate(r, roots, found)) {
  53. roots[found++] = r;
  54. printf("Root %d: %.10f\n", found, r);
  55. }
  56. }
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
=== Newton-Raphson roots (deduplicated) ===
Root 1: 8.6962148612
Root 2: -5.4892537611