]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/Misc.hs
bf8414d8e859d671e5c5c8794e63ea31680f4b0a
[numerical-analysis.git] / src / Misc.hs
1 {-# LANGUAGE RebindableSyntax #-}
2 {-# LANGUAGE ScopedTypeVariables #-}
3
4 -- | Stuff for which I'm too lazy to come up with a decent name.
5 module Misc
6 where
7
8 import NumericPrelude
9 import Algebra.Field
10 import Algebra.RealRing
11 import Algebra.ToInteger
12
13 -- | Partition the interval [@a@, @b@] into @n@ subintervals, which we
14 -- then return as a list of pairs.
15 --
16 -- Examples:
17 --
18 -- >>> partition 1 (-1) 1
19 -- [(-1.0,1.0)]
20 --
21 -- >>> partition 4 (-1) 1
22 -- [(-1.0,-0.5),(-0.5,0.0),(0.0,0.5),(0.5,1.0)]
23 --
24 partition :: (Algebra.Field.C a, Algebra.ToInteger.C b, Enum b)
25 => b -- ^ The number of subintervals to use, @n@
26 -> a -- ^ The \"left\" endpoint of the interval, @a@
27 -> a -- ^ The \"right\" endpoint of the interval, @b@
28 -> [(a,a)]
29 -- Somebody asked for zero subintervals? Ok.
30 partition 0 _ _ = []
31 partition n a b
32 | n < 0 = error "partition: asked for a negative number of subintervals"
33 | otherwise =
34 [ (xi, xj) | k <- [0..n-1],
35 let k' = fromIntegral k,
36 let xi = a + k'*h,
37 let xj = a + (k'+1)*h ]
38 where
39 coerced_n = fromIntegral $ toInteger n
40 h = (b-a)/coerced_n
41
42
43 -- | Compute the unit roundoff (machine epsilon) for this machine. We
44 -- find the largest number epsilon such that 1+epsilon <= 1. If you
45 -- request anything other than a Float or Double from this, expect
46 -- to wait a while.
47 --
48 unit_roundoff :: forall a. (Algebra.RealRing.C a, Algebra.Field.C a) => a
49 unit_roundoff =
50 head [ 1/2^(k-1) | k <- [0..], 1 + 1/(2^k) <= (1::a) ]