ex4.1.hs 874 B

12345678910111213141516171819202122232425262728293031
  1. -- Exercise 4.1
  2. -- George C. Privon
  3. -- 2023-12-22
  4. type R = Double
  5. type Derivative = (R -> R) -> R -> R
  6. -- a function to take the numerical derivative, approximated for some dt
  7. derivative :: R -> Derivative
  8. derivative dt x t = (x (t + dt/2) - x (t - dt/2)) / dt
  9. -- the function we want to take the derivative of
  10. myfunc :: R -> R
  11. myfunc x = 1/2 * x**2
  12. -- take the derivative with dt=10
  13. dOne :: R -> R
  14. dOne x = derivative 10 myfunc x
  15. -- take the derivative with dt=1
  16. dTwo :: R -> R
  17. dTwo x = derivative 1 myfunc x
  18. -- take the derivative with dt=0.1
  19. dThree :: R -> R
  20. dThree x = derivative 0.1 myfunc x
  21. -- Solution discussion
  22. -- dThree does not give an exact solution because the floating point value
  23. -- `0.1` does not have an exact finite binary representation and so is
  24. -- truncated. That truncation manifests as an inexact answer for the evaluation
  25. -- of the derivative.