derivative_numerical_approximation.sf 466 B

1234567891011121314151617181920
  1. #!/usr/bin/ruby
  2. # Numerical approximation of the derivative of a function `f(x)`, at a given value `x`.
  3. # Formula:
  4. # f'(x) = Limit_{h -> 0} (f(x + h) - f(x))/h
  5. # See also:
  6. # https://en.wikipedia.org/wiki/Derivative
  7. # https://en.wikipedia.org/wiki/Numerical_differentiation
  8. func derivative(f, x, h=1e-49) {
  9. (f(x + h) - f(x)) / h
  10. }
  11. # Example for: f(x) = x^3 + x^2
  12. # where: f'(x) = 3*x^2 + 2*x
  13. say derivative({|x| x**3 + x**2 }, 10) #=> 320