fork download
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. typedef double (*raw_fptr)(double);
  6. struct real_function;
  7. typedef double (*evaluate_function)(struct real_function*, double);
  8.  
  9. struct real_function {
  10. evaluate_function evaluate;
  11. };
  12. typedef struct real_function real_function;
  13.  
  14. double evaluate(real_function *f, double x) {
  15. if(f) {
  16. return f->evaluate(f, x);
  17. }
  18. return NAN;
  19. }
  20.  
  21. struct raw_real_function {
  22. real_function real_function_base;
  23. raw_fptr raw_function;
  24. };
  25. typedef struct raw_real_function raw_real_function;
  26.  
  27. double evaluate_raw_real_function(real_function *f_base, double x) {
  28. if(f_base) {
  29. raw_real_function *f = (raw_real_function*)f_base;
  30. return f->raw_function(x);
  31. }
  32. return NAN;
  33. }
  34.  
  35. raw_real_function make_raw_real_function(raw_fptr function) {
  36. raw_real_function result;
  37. result.raw_function = function;
  38. result.real_function_base.evaluate = evaluate_raw_real_function;
  39. return result;
  40. }
  41.  
  42. struct derive_real_function {
  43. real_function real_function_base;
  44. real_function *function_to_derive;
  45. };
  46. typedef struct derive_real_function derive_real_function;
  47.  
  48. double derive(real_function *f_base, double x) {
  49. derive_real_function *f = (derive_real_function*)f_base;
  50. double epsilon = 1e-3;
  51. double upper = evaluate(f->function_to_derive, x+epsilon);
  52. double lower = evaluate(f->function_to_derive, x-epsilon);
  53. double result = (upper - lower)/(2.0*epsilon);
  54. return result;
  55. }
  56.  
  57. derive_real_function make_derivative(real_function * function_to_derive) {
  58. derive_real_function result;
  59. result.real_function_base.evaluate = derive;
  60. result.function_to_derive = function_to_derive;
  61. return result;
  62. }
  63.  
  64. double x_cubed(double x) {
  65. return x * x * x;
  66. }
  67.  
  68. int main(int argc, char **argv) {
  69. raw_real_function x_cubed_wrapped = make_raw_real_function(x_cubed);
  70. derive_real_function derived = make_derivative(&x_cubed_wrapped.real_function_base);
  71. derive_real_function derived_twice = make_derivative(&derived.real_function_base);
  72. double x;
  73. scanf("%lf", &x);
  74. double derivative = evaluate(&derived.real_function_base, x);
  75. double second_derivative = evaluate(&derived_twice.real_function_base, x);
  76. printf("derivative of x^3 at %f = %f\n", x, derivative);
  77. printf("second derivative of x^3 at %f = %f\n", x, second_derivative);
  78. return 0;
  79. }
  80.  
Success #stdin #stdout 0s 10304KB
stdin
0.5
stdout
derivative of x^3 at 0.500000 = 0.750001
second derivative of x^3 at 0.500000 = 3.000000