瀏覽代碼

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

George C. Privon 2 年之前
父節點
當前提交
87f6714f07
共有 1 個文件被更改,包括 29 次插入0 次删除
  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%