瀏覽代碼

exercise 4.2: error dependence on x and on dt

George C. Privon 2 年之前
父節點
當前提交
1cae464232
共有 1 個文件被更改,包括 41 次插入0 次删除
  1. 41 0
      04-motion/exercises/ex4.2.hs

+ 41 - 0
04-motion/exercises/ex4.2.hs

@@ -0,0 +1,41 @@
+-- Exercise 4.2
+-- 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**3
+
+-- exact derivative of our function of interest
+dmyfunc :: R -> R
+dmyfunc x = 3 * x**2
+
+-- take the derivative with dt=1
+dOne :: R -> R
+dOne x = derivative 1 myfunc x
+
+-- compare the exact derivative with the numerical derivative using dt=1
+abserr :: R -> R
+abserr x = abs (dmyfunc x - dOne x)
+
+-- compare the exact derivative with the numerical derivative, for a fixed
+-- value, varying the dt
+abserrdt :: R -> R
+abserrdt dt = abs (dmyfunc 0.1 - derivative dt myfunc 0.1)
+
+
+-- Solution discussion
+-- a) The error introduced by the numerical derivative is a constant value of
+--    0.25.
+-- b) The error in terms of `dt` (a in the variables of the example) follows
+--    0.25*dt**2
+-- c) When x=4, a fractional error of 1% can be achieved with a
+--    dt=sqrt(0.01*48/0.25)~1.3856406460551018.
+--    When x=0.1, the same fractional error can be achieved with:
+--    dt=sqrt(0.01*0.03/0.25)~3.4641016151377546e-2