fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double func(double x){
  5. return x*x*x;
  6. }
  7.  
  8. void threepoint(double xi[], double yi[], int N, double h);
  9. void fivepoint(double xi[], double yi[], int N, double h);
  10.  
  11. void threepoint(double xi[], double yi[], int N, double h){
  12. double dy;
  13. printf("1次微係数:3点\n");
  14.  
  15. for (int i=0;i<N+1;i++) {
  16. if(i==0) {
  17. dy = (-yi[2]+4*yi[1]-3*yi[0])/(2*h);
  18. }else if(i==N) {
  19. dy = (3*yi[N]-4*yi[N-1]+yi[N-2])/(2*h);
  20. }else{
  21. dy = (yi[i+1]-yi[i-1])/(2*h);
  22. }
  23. printf("y'%d = %f\n", i+1, dy);
  24. }
  25. printf("\n");
  26. }
  27.  
  28. void fivepoint(double xi[], double yi[], int N, double h){
  29. double dy;
  30. printf("1次微係数:5点\n");
  31.  
  32. for (int i=0;i<N+1;i++) {
  33. if(i==0) {
  34. dy = (-11*yi[0]+18*yi[1]-9*yi[2]+2*yi[3])/(6*h);
  35. }else if(i==1){
  36. dy = (-2*yi[0]-3*yi[1]+6*yi[2]-yi[3])/(6*h);
  37. }
  38. else if(i==N-1) {
  39. dy = (yi[N-3]-6*yi[N-2]+3*yi[N-1]+2*yi[N])/(6*h);
  40. }else{
  41. dy = (-2*yi[i-3]+9*yi[i-2]-18*yi[i-1]+11*yi[i])/(6*h);
  42. }
  43. printf("y'%d = %f\n", i+1, dy);
  44. }
  45. printf("\n");
  46. }
  47.  
  48. int main(void) {
  49. double xl = 0;
  50. double xr = 1;
  51. double h = 0.1;
  52.  
  53. int N = (int)((xr - xl) / h);
  54.  
  55. double yi[N+1];
  56. double xi[N+1];
  57.  
  58. xi[0] = xl;
  59. yi[0] = func(xi[0]);
  60.  
  61. for (int i=1;i<N+1;i++) {
  62. xi[i] = xi[i-1] + h;
  63. yi[i] = func(xi[i]);
  64. }
  65.  
  66. threepoint(xi, yi, N, h);
  67. fivepoint(xi, yi, N, h);
  68.  
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0s 5268KB
stdin
Standard input is empty
stdout
1次微係数:3点
y'1 = -0.020000
y'2 = 0.040000
y'3 = 0.130000
y'4 = 0.280000
y'5 = 0.490000
y'6 = 0.760000
y'7 = 1.090000
y'8 = 1.480000
y'9 = 1.930000
y'10 = 2.440000
y'11 = 2.980000

1次微係数:5点
y'1 = 0.000000
y'2 = 0.030000
y'3 = 0.116667
y'4 = 0.270000
y'5 = 0.480000
y'6 = 0.750000
y'7 = 1.080000
y'8 = 1.470000
y'9 = 1.920000
y'10 = 2.430000
y'11 = 3.000000