_root_scalar.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. """
  2. Unified interfaces to root finding algorithms for real or complex
  3. scalar functions.
  4. Functions
  5. ---------
  6. - root : find a root of a scalar function.
  7. """
  8. from __future__ import division, print_function, absolute_import
  9. import numpy as np
  10. from scipy._lib.six import callable
  11. from . import zeros as optzeros
  12. __all__ = ['root_scalar']
  13. class MemoizeDer(object):
  14. """Decorator that caches the value and derivative(s) of function each
  15. time it is called.
  16. This is a simplistic memoizer that calls and caches a single value
  17. of `f(x, *args)`.
  18. It assumes that `args` does not change between invocations.
  19. It supports the use case of a root-finder where `args` is fixed,
  20. `x` changes, and only rarely, if at all, does x assume the same value
  21. more than once."""
  22. def __init__(self, fun):
  23. self.fun = fun
  24. self.vals = None
  25. self.x = None
  26. self.n_calls = 0
  27. def __call__(self, x, *args):
  28. r"""Calculate f or use cached value if available"""
  29. # Derivative may be requested before the function itself, always check
  30. if self.vals is None or x != self.x:
  31. fg = self.fun(x, *args)
  32. self.x = x
  33. self.n_calls += 1
  34. self.vals = fg[:]
  35. return self.vals[0]
  36. def fprime(self, x, *args):
  37. r"""Calculate f' or use a cached value if available"""
  38. if self.vals is None or x != self.x:
  39. self(x, *args)
  40. return self.vals[1]
  41. def fprime2(self, x, *args):
  42. r"""Calculate f'' or use a cached value if available"""
  43. if self.vals is None or x != self.x:
  44. self(x, *args)
  45. return self.vals[2]
  46. def ncalls(self):
  47. return self.n_calls
  48. def root_scalar(f, args=(), method=None, bracket=None,
  49. fprime=None, fprime2=None,
  50. x0=None, x1=None,
  51. xtol=None, rtol=None, maxiter=None,
  52. options=None):
  53. """
  54. Find a root of a scalar function.
  55. Parameters
  56. ----------
  57. f : callable
  58. A function to find a root of.
  59. args : tuple, optional
  60. Extra arguments passed to the objective function and its derivative(s).
  61. method : str, optional
  62. Type of solver. Should be one of
  63. - 'bisect' :ref:`(see here) <optimize.root_scalar-bisect>`
  64. - 'brentq' :ref:`(see here) <optimize.root_scalar-brentq>`
  65. - 'brenth' :ref:`(see here) <optimize.root_scalar-brenth>`
  66. - 'ridder' :ref:`(see here) <optimize.root_scalar-ridder>`
  67. - 'toms748' :ref:`(see here) <optimize.root_scalar-toms748>`
  68. - 'newton' :ref:`(see here) <optimize.root_scalar-newton>`
  69. - 'secant' :ref:`(see here) <optimize.root_scalar-secant>`
  70. - 'halley' :ref:`(see here) <optimize.root_scalar-halley>`
  71. bracket: A sequence of 2 floats, optional
  72. An interval bracketing a root. `f(x, *args)` must have different
  73. signs at the two endpoints.
  74. x0 : float, optional
  75. Initial guess.
  76. x1 : float, optional
  77. A second guess.
  78. fprime : bool or callable, optional
  79. If `fprime` is a boolean and is True, `f` is assumed to return the
  80. value of derivative along with the objective function.
  81. `fprime` can also be a callable returning the derivative of `f`. In
  82. this case, it must accept the same arguments as `f`.
  83. fprime2 : bool or callable, optional
  84. If `fprime2` is a boolean and is True, `f` is assumed to return the
  85. value of 1st and 2nd derivatives along with the objective function.
  86. `fprime2` can also be a callable returning the 2nd derivative of `f`.
  87. In this case, it must accept the same arguments as `f`.
  88. xtol : float, optional
  89. Tolerance (absolute) for termination.
  90. rtol : float, optional
  91. Tolerance (relative) for termination.
  92. maxiter : int, optional
  93. Maximum number of iterations.
  94. options : dict, optional
  95. A dictionary of solver options. E.g. ``k``, see
  96. :obj:`show_options()` for details.
  97. Returns
  98. -------
  99. sol : RootResults
  100. The solution represented as a ``RootResults`` object.
  101. Important attributes are: ``root`` the solution , ``converged`` a
  102. boolean flag indicating if the algorithm exited successfully and
  103. ``flag`` which describes the cause of the termination. See
  104. `RootResults` for a description of other attributes.
  105. See also
  106. --------
  107. show_options : Additional options accepted by the solvers
  108. root : Find a root of a vector function.
  109. Notes
  110. -----
  111. This section describes the available solvers that can be selected by the
  112. 'method' parameter.
  113. The default is to use the best method available for the situation
  114. presented.
  115. If a bracket is provided, it may use one of the bracketing methods.
  116. If a derivative and an initial value are specified, it may
  117. select one of the derivative-based methods.
  118. If no method is judged applicable, it will raise an Exception.
  119. Examples
  120. --------
  121. Find the root of a simple cubic
  122. >>> from scipy import optimize
  123. >>> def f(x):
  124. ... return (x**3 - 1) # only one real root at x = 1
  125. >>> def fprime(x):
  126. ... return 3*x**2
  127. The `brentq` method takes as input a bracket
  128. >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq')
  129. >>> sol.root, sol.iterations, sol.function_calls
  130. (1.0, 10, 11)
  131. The `newton` method takes as input a single point and uses the derivative(s)
  132. >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton')
  133. >>> sol.root, sol.iterations, sol.function_calls
  134. (1.0, 11, 22)
  135. The function can provide the value and derivative(s) in a single call.
  136. >>> def f_p_pp(x):
  137. ... return (x**3 - 1), 3*x**2, 6*x
  138. >>> sol = optimize.root_scalar(f_p_pp, x0=0.2, fprime=True, method='newton')
  139. >>> sol.root, sol.iterations, sol.function_calls
  140. (1.0, 11, 11)
  141. >>> sol = optimize.root_scalar(f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley')
  142. >>> sol.root, sol.iterations, sol.function_calls
  143. (1.0, 7, 8)
  144. """
  145. if not isinstance(args, tuple):
  146. args = (args,)
  147. if options is None:
  148. options = {}
  149. # fun also returns the derivative(s)
  150. is_memoized = False
  151. if fprime2 is not None and not callable(fprime2):
  152. if bool(fprime2):
  153. f = MemoizeDer(f)
  154. is_memoized = True
  155. fprime2 = f.fprime2
  156. fprime = f.fprime
  157. else:
  158. fprime2 = None
  159. if fprime is not None and not callable(fprime):
  160. if bool(fprime):
  161. f = MemoizeDer(f)
  162. is_memoized = True
  163. fprime = f.fprime
  164. else:
  165. fprime = None
  166. # respect solver-specific default tolerances - only pass in if actually set
  167. kwargs = {}
  168. for k in ['xtol', 'rtol', 'maxiter']:
  169. v = locals().get(k)
  170. if v is not None:
  171. kwargs[k] = v
  172. # Set any solver-specific options
  173. if options:
  174. kwargs.update(options)
  175. # Always request full_output from the underlying method as _root_scalar
  176. # always returns a RootResults object
  177. kwargs.update(full_output=True, disp=False)
  178. # Pick a method if not specified.
  179. # Use the "best" method available for the situation.
  180. if not method:
  181. if bracket:
  182. method = 'brentq'
  183. elif x0 is not None:
  184. if fprime:
  185. if fprime2:
  186. method = 'halley'
  187. else:
  188. method = 'newton'
  189. else:
  190. method = 'secant'
  191. if not method:
  192. raise ValueError('Unable to select a solver as neither bracket '
  193. 'nor starting point provided.')
  194. meth = method.lower()
  195. map2underlying = {'halley': 'newton', 'secant': 'newton'}
  196. try:
  197. methodc = getattr(optzeros, map2underlying.get(meth, meth))
  198. except AttributeError:
  199. raise ValueError('Unknown solver %s' % meth)
  200. if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']:
  201. if not isinstance(bracket, (list, tuple, np.ndarray)):
  202. raise ValueError('Bracket needed for %s' % method)
  203. a, b = bracket[:2]
  204. r, sol = methodc(f, a, b, args=args, **kwargs)
  205. elif meth in ['secant']:
  206. if x0 is None:
  207. raise ValueError('x0 must not be None for %s' % method)
  208. if x1 is None:
  209. raise ValueError('x1 must not be None for %s' % method)
  210. if 'xtol' in kwargs:
  211. kwargs['tol'] = kwargs.pop('xtol')
  212. r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None,
  213. x1=x1, **kwargs)
  214. elif meth in ['newton']:
  215. if x0 is None:
  216. raise ValueError('x0 must not be None for %s' % method)
  217. if not fprime:
  218. raise ValueError('fprime must be specified for %s' % method)
  219. if 'xtol' in kwargs:
  220. kwargs['tol'] = kwargs.pop('xtol')
  221. r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None,
  222. **kwargs)
  223. elif meth in ['halley']:
  224. if x0 is None:
  225. raise ValueError('x0 must not be None for %s' % method)
  226. if not fprime:
  227. raise ValueError('fprime must be specified for %s' % method)
  228. if not fprime2:
  229. raise ValueError('fprime2 must be specified for %s' % method)
  230. if 'xtol' in kwargs:
  231. kwargs['tol'] = kwargs.pop('xtol')
  232. r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs)
  233. else:
  234. raise ValueError('Unknown solver %s' % method)
  235. if is_memoized:
  236. # Replace the function_calls count with the memoized count.
  237. # Avoids double and triple-counting.
  238. n_calls = f.n_calls
  239. sol.function_calls = n_calls
  240. return sol
  241. def _root_scalar_brentq_doc():
  242. r"""
  243. Options
  244. -------
  245. args : tuple, optional
  246. Extra arguments passed to the objective function.
  247. xtol : float, optional
  248. Tolerance (absolute) for termination.
  249. rtol : float, optional
  250. Tolerance (relative) for termination.
  251. maxiter : int, optional
  252. Maximum number of iterations.
  253. options: dict, optional
  254. Specifies any method-specific options not covered above
  255. """
  256. pass
  257. def _root_scalar_brenth_doc():
  258. r"""
  259. Options
  260. -------
  261. args : tuple, optional
  262. Extra arguments passed to the objective function.
  263. xtol : float, optional
  264. Tolerance (absolute) for termination.
  265. rtol : float, optional
  266. Tolerance (relative) for termination.
  267. maxiter : int, optional
  268. Maximum number of iterations.
  269. options: dict, optional
  270. Specifies any method-specific options not covered above
  271. """
  272. pass
  273. def _root_scalar_toms748_doc():
  274. r"""
  275. Options
  276. -------
  277. args : tuple, optional
  278. Extra arguments passed to the objective function.
  279. xtol : float, optional
  280. Tolerance (absolute) for termination.
  281. rtol : float, optional
  282. Tolerance (relative) for termination.
  283. maxiter : int, optional
  284. Maximum number of iterations.
  285. options: dict, optional
  286. Specifies any method-specific options not covered above
  287. """
  288. pass
  289. def _root_scalar_secant_doc():
  290. r"""
  291. Options
  292. -------
  293. args : tuple, optional
  294. Extra arguments passed to the objective function.
  295. xtol : float, optional
  296. Tolerance (absolute) for termination.
  297. rtol : float, optional
  298. Tolerance (relative) for termination.
  299. maxiter : int, optional
  300. Maximum number of iterations.
  301. x0 : float, required
  302. Initial guess.
  303. x1 : float, required
  304. A second guess.
  305. options: dict, optional
  306. Specifies any method-specific options not covered above
  307. """
  308. pass
  309. def _root_scalar_newton_doc():
  310. r"""
  311. Options
  312. -------
  313. args : tuple, optional
  314. Extra arguments passed to the objective function and its derivative.
  315. xtol : float, optional
  316. Tolerance (absolute) for termination.
  317. rtol : float, optional
  318. Tolerance (relative) for termination.
  319. maxiter : int, optional
  320. Maximum number of iterations.
  321. x0 : float, required
  322. Initial guess.
  323. fprime : bool or callable, optional
  324. If `fprime` is a boolean and is True, `f` is assumed to return the
  325. value of derivative along with the objective function.
  326. `fprime` can also be a callable returning the derivative of `f`. In
  327. this case, it must accept the same arguments as `f`.
  328. options: dict, optional
  329. Specifies any method-specific options not covered above
  330. """
  331. pass
  332. def _root_scalar_halley_doc():
  333. r"""
  334. Options
  335. -------
  336. args : tuple, optional
  337. Extra arguments passed to the objective function and its derivatives.
  338. xtol : float, optional
  339. Tolerance (absolute) for termination.
  340. rtol : float, optional
  341. Tolerance (relative) for termination.
  342. maxiter : int, optional
  343. Maximum number of iterations.
  344. x0 : float, required
  345. Initial guess.
  346. fprime : bool or callable, required
  347. If `fprime` is a boolean and is True, `f` is assumed to return the
  348. value of derivative along with the objective function.
  349. `fprime` can also be a callable returning the derivative of `f`. In
  350. this case, it must accept the same arguments as `f`.
  351. fprime2 : bool or callable, required
  352. If `fprime2` is a boolean and is True, `f` is assumed to return the
  353. value of 1st and 2nd derivatives along with the objective function.
  354. `fprime2` can also be a callable returning the 2nd derivative of `f`.
  355. In this case, it must accept the same arguments as `f`.
  356. options: dict, optional
  357. Specifies any method-specific options not covered above
  358. """
  359. pass
  360. def _root_scalar_ridder_doc():
  361. r"""
  362. Options
  363. -------
  364. args : tuple, optional
  365. Extra arguments passed to the objective function.
  366. xtol : float, optional
  367. Tolerance (absolute) for termination.
  368. rtol : float, optional
  369. Tolerance (relative) for termination.
  370. maxiter : int, optional
  371. Maximum number of iterations.
  372. options: dict, optional
  373. Specifies any method-specific options not covered above
  374. """
  375. pass
  376. def _root_scalar_bisect_doc():
  377. r"""
  378. Options
  379. -------
  380. args : tuple, optional
  381. Extra arguments passed to the objective function.
  382. xtol : float, optional
  383. Tolerance (absolute) for termination.
  384. rtol : float, optional
  385. Tolerance (relative) for termination.
  386. maxiter : int, optional
  387. Maximum number of iterations.
  388. options: dict, optional
  389. Specifies any method-specific options not covered above
  390. """
  391. pass