Browse Source

exercise 4.1: floating point truncation and finite precision

George C. Privon 2 years ago
parent
commit
edfa9bcbc8
2 changed files with 32 additions and 0 deletions
  1. 28 0
      04-motion/exercises/ex4.1.hs
  2. 4 0
      errata

+ 28 - 0
04-motion/exercises/ex4.1.hs

@@ -0,0 +1,28 @@
+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 = 1/2 * x**2
+
+-- take the derivative with dt=10
+dOne :: R -> R
+dOne x = derivative 10 myfunc x
+
+-- take the derivative with dt=1
+dTwo :: R -> R
+dTwo x = derivative 1 myfunc x
+
+-- take the derivative with dt=0.1
+dThree :: R -> R
+dThree x = derivative 0.1 myfunc x
+
+-- Solution discussion
+-- dThree does not give an exact solution because the floating point value
+-- `0.1` does not have an exact finite binary representation and so is
+-- truncated. That truncation manifests as an inexact answer for the evaluation
+-- of the derivative.

+ 4 - 0
errata

@@ -5,3 +5,7 @@
 # Chapter 3
 
 - page 23 (missing text in square brackets): "Here b is an expression of type Bool called the condition[, c] is called the consequent[, and a] is called the alternative."
+
+# Chapter 4
+
+- Exercise 4.1 only comes out correctly if f(x) is written with `1/2` and not as 0.5 because the latter introduces floating point approximation/truncation issues regardless of what dt is provided to `derivative`.