fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <math.h>
  5.  
  6. #define EPSILON (1e-12)
  7.  
  8. int verbose=0;
  9.  
  10. double func( double x ) /* 解く方程式 */
  11. {
  12. return sin(x) - 0.2;
  13. }
  14.  
  15.  
  16. double diff( double x ) /*導関数 */
  17. {
  18. return cos(x);
  19. }
  20.  
  21.  
  22. void iterate( double x0, int n )
  23. {
  24. double y0, x, y, delta;
  25.  
  26. y0 = func(x0);
  27. x = x0 + ( delta = - y0 / diff( x0 ) ); /* 接線の x 切片 */
  28. if (n++ > 100) {
  29. printf( "Too Many Recursions\n" );
  30. return;
  31. }
  32.  
  33. y = func(x);
  34.  
  35. if (verbose) {
  36. printf( "%03d> %20.14lf %16.1le %10.1le\n", n, x, delta, y );
  37. }
  38.  
  39. if (y == 0) {
  40. printf( "Ans(%03d): %20.14lf %16.1le %10.1le %10.1le\n",
  41. n, x, func(x*(1-EPSILON)), y, func(x*(1+EPSILON)) );
  42. } else if (fabs(delta) < fabs(x)*EPSILON) {
  43. printf( "Ans(%03d): %20.14lf %16.1le %10.1le %10.1le\n",
  44. n, x, func(x*(1-EPSILON)), y, func(x*(1+EPSILON)) );
  45. } else {
  46. iterate( x, n );
  47. }
  48. }
  49.  
  50.  
  51. int main (int argc, char **argv) {
  52. double x, y;
  53. double xfrom, xto;
  54. int xsteps, xidx;
  55. char ch;
  56.  
  57. while (( ch = getopt(argc,argv,"v")) != -1 ) {
  58. if ( ch == 'v' ) { verbose = 1; }
  59. }
  60.  
  61. printf("x: from to steps> ");
  62. scanf( "%lf %lf %d", &xfrom, &xto, &xsteps );
  63.  
  64. for( xidx=0; xidx<=xsteps; xidx++ ) {
  65. x = (xfrom * (xsteps - xidx) + xto * xidx) / xsteps;
  66. if ((y = func(x)) == 0) {
  67. printf( "Ans(%03d): %20.14lf %16.5le %12.5le %12.5le\n",
  68. 0, x, func(x*(1-EPSILON)), y, func(x*(1+EPSILON)) );
  69. } else {
  70. if (verbose) {
  71. printf( "%03d> %20.14lf\n", 0, x );
  72. }
  73. iterate( x, 0 );
  74. }
  75. }
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0s 4348KB
stdin
-4 4 10
stdout
x: from to steps> Ans(005):    -3.34295057438012         -3.3e-12   -5.6e-17    3.3e-12
Ans(004):    -3.34295057438012         -3.3e-12   -5.6e-17    3.3e-12
Ans(006):    -3.34295057438012         -3.3e-12   -5.6e-17    3.3e-12
Ans(008):    46.92253188305657          4.6e-11   -3.4e-15   -4.6e-11
Ans(006):     0.20135792079033         -2.0e-13    0.0e+00    2.0e-13
Ans(004):     0.20135792079033         -2.0e-13    2.8e-17    2.0e-13
Ans(005):     0.20135792079033         -2.0e-13    0.0e+00    2.0e-13
Ans(006):    28.07297596151781          2.8e-11   -5.8e-16   -2.8e-11
Ans(005):     2.94023473279946          2.9e-12    1.9e-16   -2.9e-12
Ans(004):     2.94023473279946          2.9e-12    1.9e-16   -2.9e-12
Ans(006):     2.94023473279946          2.9e-12    1.9e-16   -2.9e-12