/
RootFinding.hs
258 lines (229 loc) · 8.45 KB
/
RootFinding.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, CPP #-}
-- |
-- Module : Numeric.RootFinding
-- Copyright : (c) 2011 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : portable
--
-- Haskell functions for finding the roots of real functions of real arguments.
module Numeric.RootFinding
( -- * Data types
Root(..)
, fromRoot
, Tolerance(..)
, withinTolerance
-- * Ridders algorithm
, RiddersParam(..)
, ridders
-- * Newton-Raphson algorithm
, newtonRaphson
-- * References
-- $references
) where
import Control.Applicative (Alternative(..), Applicative(..))
import Control.Monad (MonadPlus(..), ap)
import Data.Data (Data, Typeable)
import Data.Default.Class
#if __GLASGOW_HASKELL__ > 704
import GHC.Generics (Generic)
#endif
import Numeric.MathFunctions.Comparison (within,eqRelErr)
import Numeric.MathFunctions.Constants (m_epsilon)
----------------------------------------------------------------
-- Data types
----------------------------------------------------------------
-- | The result of searching for a root of a mathematical function.
data Root a = NotBracketed
-- ^ The function does not have opposite signs when
-- evaluated at the lower and upper bounds of the search.
| SearchFailed
-- ^ The search failed to converge to within the given
-- error tolerance after the given number of iterations.
| Root a
-- ^ A root was successfully found.
deriving (Eq, Read, Show, Typeable, Data
#if __GLASGOW_HASKELL__ > 704
, Generic
#endif
)
instance Functor Root where
fmap _ NotBracketed = NotBracketed
fmap _ SearchFailed = SearchFailed
fmap f (Root a) = Root (f a)
instance Monad Root where
NotBracketed >>= _ = NotBracketed
SearchFailed >>= _ = SearchFailed
Root a >>= m = m a
return = Root
instance MonadPlus Root where
mzero = SearchFailed
r@(Root _) `mplus` _ = r
_ `mplus` p = p
instance Applicative Root where
pure = Root
(<*>) = ap
instance Alternative Root where
empty = SearchFailed
r@(Root _) <|> _ = r
_ <|> p = p
-- | Returns either the result of a search for a root, or the default
-- value if the search failed.
fromRoot :: a -- ^ Default value.
-> Root a -- ^ Result of search for a root.
-> a
fromRoot _ (Root a) = a
fromRoot a _ = a
-- | Error tolerance for finding root. It describes when root finding
-- algorithm should stop trying to improve approximation.
data Tolerance
= RelTol !Double
-- ^ Relative error tolerance. Given @RelTol ε@ two values are
-- considered approximately equal if
-- \[ |a - b| / |\operatorname{max}(a,b)} < \vareps \]
| AbsTol !Double
-- ^ Absolute error tolerance. Given @AbsTol δ@ two values are
-- considered approximately equal if \[ |a - b| < \delta \].
-- Note that @AbsTol 0@ could be used to require to find
-- approximation within machine precision.
deriving (Eq, Read, Show, Typeable, Data
#if __GLASGOW_HASKELL__ > 704
, Generic
#endif
)
withinTolerance :: Tolerance -> Double -> Double -> Bool
withinTolerance (RelTol eps) a b = eqRelErr eps a b
-- NOTE: `<=` is needed to allow 0 absolute tolerance which is used to
-- describe precision of 1ulp
withinTolerance (AbsTol tol) a b = abs (a - b) <= tol
----------------------------------------------------------------
-- Ridders algorithm
----------------------------------------------------------------
-- | Parameters for 'ridders' root finding
data RiddersParam = RiddersParam
{ riddersMaxIter :: !Int
-- ^ Maximum number of iterations.
, riddersTol :: !Tolerance
-- ^ Error tolerance for root approximation.
}
deriving (Eq, Read, Show, Typeable, Data
#if __GLASGOW_HASKELL__ > 704
, Generic
#endif
)
instance Default RiddersParam where
def = RiddersParam
{ riddersMaxIter = 100
, riddersTol = RelTol (4 * m_epsilon)
}
-- | Use the method of Ridders[Ridders1979] to compute a root of a
-- function. It doesn't require derivative and provide quadratic
-- convergence (number of significant digits grows quadratically
-- with number of iterations).
--
-- The function must have opposite signs when evaluated at the lower
-- and upper bounds of the search (i.e. the root must be
-- bracketed). If there's more that one root in the bracket
-- iteration will converge to some root in the bracket.
ridders :: RiddersParam
-- ^ Absolute error tolerance. Iterations will be stopped when
-- difference between root and estimate is less than
-- tolerance or when precision couldn't be improved further
-- (root is within 1 ulp).
-> (Double,Double)
-- ^ Lower and upper bounds for the search.
-> (Double -> Double)
-- ^ Function to find the roots of.
-> Root Double
ridders p (lo,hi) f
| flo == 0 = Root lo
| fhi == 0 = Root hi
-- root is not bracketed
| flo*fhi > 0 = NotBracketed
-- Ensure that a<b in iterations
| lo < hi = go lo flo hi fhi 0
| otherwise = go hi fhi lo flo 0
where
!flo = f lo
!fhi = f hi
--
go !a !fa !b !fb !i
-- Root is bracketed within 1 ulp. No improvement could be made
| within 1 a b = Root a
-- Root is found. Check that f(m) == 0 is nessesary to ensure
-- that root is never passed to 'go'
| fm == 0 = Root m
| fn == 0 = Root n
| withinTolerance (riddersTol p) a b = Root n
-- Too many iterations performed. Fail
| i >= riddersMaxIter p = SearchFailed
-- Ridder's approximation coincide with one of old bounds or
-- went out of (a,b) range due to numerical problems. Revert
-- to bisection
| n <= a || n >= b = case () of
_| fm*fa < 0 -> go a fa m fm (i+1)
| otherwise -> go m fm b fb (i+1)
-- Proceed as usual
| fn*fm < 0 = go n fn m fm (i+1)
| fn*fa < 0 = go a fa n fn (i+1)
| otherwise = go n fn b fb (i+1)
where
dm = (b - a) * 0.5
-- Mean point
!m = a + dm
!fm = f m
-- Ridders update
!n = m - signum (fb - fa) * dm * fm / sqrt(fm*fm - fa*fb)
!fn = f n
----------------------------------------------------------------
-- Newton-Raphson algorithm
----------------------------------------------------------------
-- | Solve equation using Newton-Raphson iterations.
--
-- This method require both initial guess and bounds for root. If
-- Newton step takes us out of bounds on root function reverts to
-- bisection.
newtonRaphson
:: Double
-- ^ Required precision
-> (Double,Double,Double)
-- ^ (lower bound, initial guess, upper bound). Iterations will no
-- go outside of the interval
-> (Double -> (Double,Double))
-- ^ Function to finds roots. It returns pair of function value and
-- its derivative
-> Root Double
newtonRaphson !prec (!low,!guess,!hi) function
= go low guess hi
where
go !xMin !x !xMax
| f == 0 = Root x
| abs (dx / x) < prec = Root x
| otherwise = go xMin' x' xMax'
where
(f,f') = function x
-- Calculate Newton-Raphson step
delta | f' == 0 = error "handle f'==0"
| otherwise = f / f'
-- Calculate new approximation and actual change of approximation
(dx,x') | z <= xMin = let d = 0.5*(x - xMin) in (d, x - d)
| z >= xMax = let d = 0.5*(x - xMax) in (d, x - d)
| otherwise = (delta, z)
where z = x - delta
-- Update root bracket
xMin' | dx < 0 = x
| otherwise = xMin
xMax' | dx > 0 = x
| otherwise = xMax
-- $references
--
-- * Ridders, C.F.J. (1979) A new algorithm for computing a single
-- root of a real continuous function.
-- /IEEE Transactions on Circuits and Systems/ 26:979–980.
--
-- * Press W.H.; Teukolsky S.A.; Vetterling W.T.; Flannery B.P.
-- (2007). \"Section 9.2.1. Ridders' Method\". /Numerical Recipes: The
-- Art of Scientific Computing (3rd ed.)./ New York: Cambridge
-- University Press. ISBN 978-0-521-88068-8.