ex4.2.hs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. -- Exercise 4.2
  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 = x**3
  12. -- exact derivative of our function of interest
  13. dmyfunc :: R -> R
  14. dmyfunc x = 3 * x**2
  15. -- take the derivative with dt=1
  16. dOne :: R -> R
  17. dOne x = derivative 1 myfunc x
  18. -- compare the exact derivative with the numerical derivative using dt=1
  19. abserr :: R -> R
  20. abserr x = abs (dmyfunc x - dOne x)
  21. -- compare the exact derivative with the numerical derivative, for a fixed
  22. -- value, varying the dt
  23. abserrdt :: R -> R
  24. abserrdt dt = abs (dmyfunc 0.1 - derivative dt myfunc 0.1)
  25. -- Solution discussion
  26. -- a) The error introduced by the numerical derivative is a constant value of
  27. -- 0.25.
  28. -- b) The error in terms of `dt` (a in the variables of the example) follows
  29. -- 0.25*dt**2
  30. -- c) When x=4, a fractional error of 1% can be achieved with a
  31. -- dt=sqrt(0.01*48/0.25)~1.3856406460551018.
  32. -- When x=0.1, the same fractional error can be achieved with:
  33. -- dt=sqrt(0.01*0.03/0.25)~3.4641016151377546e-2