Răsfoiți Sursa

exercise 4.3: a function and argument with a >10% error for dt=0.01

George C. Privon 2 ani în urmă
părinte
comite
87f6714f07
1 a modificat fișierele cu 29 adăugiri și 0 ștergeri
  1. 29 0
      04-motion/exercises/ex4.3.hs

+ 29 - 0
04-motion/exercises/ex4.3.hs

@@ -0,0 +1,29 @@
+-- Exercise 4.3
+-- George C. Privon
+-- 2023-12-22
+type R = Double
+type Derivative = (R -> R) -> R -> R
+
+-- a function to take the numerical derivative, approximated for some dt
+derivative :: R -> Derivative
+derivative dt x t = (x (t + dt/2) - x (t - dt/2)) / dt
+
+-- the function we want to take the derivative of
+myfunc :: R -> R
+myfunc x = x**4
+
+-- exact derivative of our function of interest
+dmyfunc :: R -> R
+dmyfunc x = 4 * x**3
+
+-- take the derivative with dt=1
+dOne :: R -> R
+dOne x = derivative 0.01 myfunc x
+
+-- compare the exact derivative with the numerical derivative using dt=1
+relabserr :: R -> R
+relabserr x = abs (dmyfunc x - dOne x) / dmyfunc x
+
+-- Solution
+-- The derivative of f(x) = x**4, evaluated at x=0.01 with dt=0.01 produces a
+-- relative error of 25%