_zeros_py.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. import warnings
  2. from collections import namedtuple
  3. import operator
  4. from . import _zeros
  5. import numpy as np
  6. _iter = 100
  7. _xtol = 2e-12
  8. _rtol = 4 * np.finfo(float).eps
  9. __all__ = ['newton', 'bisect', 'ridder', 'brentq', 'brenth', 'toms748',
  10. 'RootResults']
  11. # Must agree with CONVERGED, SIGNERR, CONVERR, ... in zeros.h
  12. _ECONVERGED = 0
  13. _ESIGNERR = -1
  14. _ECONVERR = -2
  15. _EVALUEERR = -3
  16. _EINPROGRESS = 1
  17. CONVERGED = 'converged'
  18. SIGNERR = 'sign error'
  19. CONVERR = 'convergence error'
  20. VALUEERR = 'value error'
  21. INPROGRESS = 'No error'
  22. flag_map = {_ECONVERGED: CONVERGED, _ESIGNERR: SIGNERR, _ECONVERR: CONVERR,
  23. _EVALUEERR: VALUEERR, _EINPROGRESS: INPROGRESS}
  24. class RootResults:
  25. """Represents the root finding result.
  26. Attributes
  27. ----------
  28. root : float
  29. Estimated root location.
  30. iterations : int
  31. Number of iterations needed to find the root.
  32. function_calls : int
  33. Number of times the function was called.
  34. converged : bool
  35. True if the routine converged.
  36. flag : str
  37. Description of the cause of termination.
  38. """
  39. def __init__(self, root, iterations, function_calls, flag):
  40. self.root = root
  41. self.iterations = iterations
  42. self.function_calls = function_calls
  43. self.converged = flag == _ECONVERGED
  44. self.flag = None
  45. try:
  46. self.flag = flag_map[flag]
  47. except KeyError:
  48. self.flag = 'unknown error %d' % (flag,)
  49. def __repr__(self):
  50. attrs = ['converged', 'flag', 'function_calls',
  51. 'iterations', 'root']
  52. m = max(map(len, attrs)) + 1
  53. return '\n'.join([a.rjust(m) + ': ' + repr(getattr(self, a))
  54. for a in attrs])
  55. def results_c(full_output, r):
  56. if full_output:
  57. x, funcalls, iterations, flag = r
  58. results = RootResults(root=x,
  59. iterations=iterations,
  60. function_calls=funcalls,
  61. flag=flag)
  62. return x, results
  63. else:
  64. return r
  65. def _results_select(full_output, r):
  66. """Select from a tuple of (root, funccalls, iterations, flag)"""
  67. x, funcalls, iterations, flag = r
  68. if full_output:
  69. results = RootResults(root=x,
  70. iterations=iterations,
  71. function_calls=funcalls,
  72. flag=flag)
  73. return x, results
  74. return x
  75. def newton(func, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50,
  76. fprime2=None, x1=None, rtol=0.0,
  77. full_output=False, disp=True):
  78. """
  79. Find a zero of a real or complex function using the Newton-Raphson
  80. (or secant or Halley's) method.
  81. Find a zero of the scalar-valued function `func` given a nearby scalar
  82. starting point `x0`.
  83. The Newton-Raphson method is used if the derivative `fprime` of `func`
  84. is provided, otherwise the secant method is used. If the second order
  85. derivative `fprime2` of `func` is also provided, then Halley's method is
  86. used.
  87. If `x0` is a sequence with more than one item, `newton` returns an array:
  88. the zeros of the function from each (scalar) starting point in `x0`.
  89. In this case, `func` must be vectorized to return a sequence or array of
  90. the same shape as its first argument. If `fprime` (`fprime2`) is given,
  91. then its return must also have the same shape: each element is the first
  92. (second) derivative of `func` with respect to its only variable evaluated
  93. at each element of its first argument.
  94. `newton` is for finding roots of a scalar-valued functions of a single
  95. variable. For problems involving several variables, see `root`.
  96. Parameters
  97. ----------
  98. func : callable
  99. The function whose zero is wanted. It must be a function of a
  100. single variable of the form ``f(x,a,b,c...)``, where ``a,b,c...``
  101. are extra arguments that can be passed in the `args` parameter.
  102. x0 : float, sequence, or ndarray
  103. An initial estimate of the zero that should be somewhere near the
  104. actual zero. If not scalar, then `func` must be vectorized and return
  105. a sequence or array of the same shape as its first argument.
  106. fprime : callable, optional
  107. The derivative of the function when available and convenient. If it
  108. is None (default), then the secant method is used.
  109. args : tuple, optional
  110. Extra arguments to be used in the function call.
  111. tol : float, optional
  112. The allowable error of the zero value. If `func` is complex-valued,
  113. a larger `tol` is recommended as both the real and imaginary parts
  114. of `x` contribute to ``|x - x0|``.
  115. maxiter : int, optional
  116. Maximum number of iterations.
  117. fprime2 : callable, optional
  118. The second order derivative of the function when available and
  119. convenient. If it is None (default), then the normal Newton-Raphson
  120. or the secant method is used. If it is not None, then Halley's method
  121. is used.
  122. x1 : float, optional
  123. Another estimate of the zero that should be somewhere near the
  124. actual zero. Used if `fprime` is not provided.
  125. rtol : float, optional
  126. Tolerance (relative) for termination.
  127. full_output : bool, optional
  128. If `full_output` is False (default), the root is returned.
  129. If True and `x0` is scalar, the return value is ``(x, r)``, where ``x``
  130. is the root and ``r`` is a `RootResults` object.
  131. If True and `x0` is non-scalar, the return value is ``(x, converged,
  132. zero_der)`` (see Returns section for details).
  133. disp : bool, optional
  134. If True, raise a RuntimeError if the algorithm didn't converge, with
  135. the error message containing the number of iterations and current
  136. function value. Otherwise, the convergence status is recorded in a
  137. `RootResults` return object.
  138. Ignored if `x0` is not scalar.
  139. *Note: this has little to do with displaying, however,
  140. the `disp` keyword cannot be renamed for backwards compatibility.*
  141. Returns
  142. -------
  143. root : float, sequence, or ndarray
  144. Estimated location where function is zero.
  145. r : `RootResults`, optional
  146. Present if ``full_output=True`` and `x0` is scalar.
  147. Object containing information about the convergence. In particular,
  148. ``r.converged`` is True if the routine converged.
  149. converged : ndarray of bool, optional
  150. Present if ``full_output=True`` and `x0` is non-scalar.
  151. For vector functions, indicates which elements converged successfully.
  152. zero_der : ndarray of bool, optional
  153. Present if ``full_output=True`` and `x0` is non-scalar.
  154. For vector functions, indicates which elements had a zero derivative.
  155. See Also
  156. --------
  157. root_scalar : interface to root solvers for scalar functions
  158. root : interface to root solvers for multi-input, multi-output functions
  159. Notes
  160. -----
  161. The convergence rate of the Newton-Raphson method is quadratic,
  162. the Halley method is cubic, and the secant method is
  163. sub-quadratic. This means that if the function is well-behaved
  164. the actual error in the estimated zero after the nth iteration
  165. is approximately the square (cube for Halley) of the error
  166. after the (n-1)th step. However, the stopping criterion used
  167. here is the step size and there is no guarantee that a zero
  168. has been found. Consequently, the result should be verified.
  169. Safer algorithms are brentq, brenth, ridder, and bisect,
  170. but they all require that the root first be bracketed in an
  171. interval where the function changes sign. The brentq algorithm
  172. is recommended for general use in one dimensional problems
  173. when such an interval has been found.
  174. When `newton` is used with arrays, it is best suited for the following
  175. types of problems:
  176. * The initial guesses, `x0`, are all relatively the same distance from
  177. the roots.
  178. * Some or all of the extra arguments, `args`, are also arrays so that a
  179. class of similar problems can be solved together.
  180. * The size of the initial guesses, `x0`, is larger than O(100) elements.
  181. Otherwise, a naive loop may perform as well or better than a vector.
  182. Examples
  183. --------
  184. >>> import numpy as np
  185. >>> import matplotlib.pyplot as plt
  186. >>> from scipy import optimize
  187. >>> def f(x):
  188. ... return (x**3 - 1) # only one real root at x = 1
  189. ``fprime`` is not provided, use the secant method:
  190. >>> root = optimize.newton(f, 1.5)
  191. >>> root
  192. 1.0000000000000016
  193. >>> root = optimize.newton(f, 1.5, fprime2=lambda x: 6 * x)
  194. >>> root
  195. 1.0000000000000016
  196. Only ``fprime`` is provided, use the Newton-Raphson method:
  197. >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2)
  198. >>> root
  199. 1.0
  200. Both ``fprime2`` and ``fprime`` are provided, use Halley's method:
  201. >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2,
  202. ... fprime2=lambda x: 6 * x)
  203. >>> root
  204. 1.0
  205. When we want to find zeros for a set of related starting values and/or
  206. function parameters, we can provide both of those as an array of inputs:
  207. >>> f = lambda x, a: x**3 - a
  208. >>> fder = lambda x, a: 3 * x**2
  209. >>> rng = np.random.default_rng()
  210. >>> x = rng.standard_normal(100)
  211. >>> a = np.arange(-50, 50)
  212. >>> vec_res = optimize.newton(f, x, fprime=fder, args=(a, ), maxiter=200)
  213. The above is the equivalent of solving for each value in ``(x, a)``
  214. separately in a for-loop, just faster:
  215. >>> loop_res = [optimize.newton(f, x0, fprime=fder, args=(a0,),
  216. ... maxiter=200)
  217. ... for x0, a0 in zip(x, a)]
  218. >>> np.allclose(vec_res, loop_res)
  219. True
  220. Plot the results found for all values of ``a``:
  221. >>> analytical_result = np.sign(a) * np.abs(a)**(1/3)
  222. >>> fig, ax = plt.subplots()
  223. >>> ax.plot(a, analytical_result, 'o')
  224. >>> ax.plot(a, vec_res, '.')
  225. >>> ax.set_xlabel('$a$')
  226. >>> ax.set_ylabel('$x$ where $f(x, a)=0$')
  227. >>> plt.show()
  228. """
  229. if tol <= 0:
  230. raise ValueError("tol too small (%g <= 0)" % tol)
  231. maxiter = operator.index(maxiter)
  232. if maxiter < 1:
  233. raise ValueError("maxiter must be greater than 0")
  234. if np.size(x0) > 1:
  235. return _array_newton(func, x0, fprime, args, tol, maxiter, fprime2,
  236. full_output)
  237. # Convert to float (don't use float(x0); this works also for complex x0)
  238. p0 = 1.0 * x0
  239. funcalls = 0
  240. if fprime is not None:
  241. # Newton-Raphson method
  242. for itr in range(maxiter):
  243. # first evaluate fval
  244. fval = func(p0, *args)
  245. funcalls += 1
  246. # If fval is 0, a root has been found, then terminate
  247. if fval == 0:
  248. return _results_select(
  249. full_output, (p0, funcalls, itr, _ECONVERGED))
  250. fder = fprime(p0, *args)
  251. funcalls += 1
  252. if fder == 0:
  253. msg = "Derivative was zero."
  254. if disp:
  255. msg += (
  256. " Failed to converge after %d iterations, value is %s."
  257. % (itr + 1, p0))
  258. raise RuntimeError(msg)
  259. warnings.warn(msg, RuntimeWarning)
  260. return _results_select(
  261. full_output, (p0, funcalls, itr + 1, _ECONVERR))
  262. newton_step = fval / fder
  263. if fprime2:
  264. fder2 = fprime2(p0, *args)
  265. funcalls += 1
  266. # Halley's method:
  267. # newton_step /= (1.0 - 0.5 * newton_step * fder2 / fder)
  268. # Only do it if denominator stays close enough to 1
  269. # Rationale: If 1-adj < 0, then Halley sends x in the
  270. # opposite direction to Newton. Doesn't happen if x is close
  271. # enough to root.
  272. adj = newton_step * fder2 / fder / 2
  273. if np.abs(adj) < 1:
  274. newton_step /= 1.0 - adj
  275. p = p0 - newton_step
  276. if np.isclose(p, p0, rtol=rtol, atol=tol):
  277. return _results_select(
  278. full_output, (p, funcalls, itr + 1, _ECONVERGED))
  279. p0 = p
  280. else:
  281. # Secant method
  282. if x1 is not None:
  283. if x1 == x0:
  284. raise ValueError("x1 and x0 must be different")
  285. p1 = x1
  286. else:
  287. eps = 1e-4
  288. p1 = x0 * (1 + eps)
  289. p1 += (eps if p1 >= 0 else -eps)
  290. q0 = func(p0, *args)
  291. funcalls += 1
  292. q1 = func(p1, *args)
  293. funcalls += 1
  294. if abs(q1) < abs(q0):
  295. p0, p1, q0, q1 = p1, p0, q1, q0
  296. for itr in range(maxiter):
  297. if q1 == q0:
  298. if p1 != p0:
  299. msg = "Tolerance of %s reached." % (p1 - p0)
  300. if disp:
  301. msg += (
  302. " Failed to converge after %d iterations, value is %s."
  303. % (itr + 1, p1))
  304. raise RuntimeError(msg)
  305. warnings.warn(msg, RuntimeWarning)
  306. p = (p1 + p0) / 2.0
  307. return _results_select(
  308. full_output, (p, funcalls, itr + 1, _ECONVERGED))
  309. else:
  310. if abs(q1) > abs(q0):
  311. p = (-q0 / q1 * p1 + p0) / (1 - q0 / q1)
  312. else:
  313. p = (-q1 / q0 * p0 + p1) / (1 - q1 / q0)
  314. if np.isclose(p, p1, rtol=rtol, atol=tol):
  315. return _results_select(
  316. full_output, (p, funcalls, itr + 1, _ECONVERGED))
  317. p0, q0 = p1, q1
  318. p1 = p
  319. q1 = func(p1, *args)
  320. funcalls += 1
  321. if disp:
  322. msg = ("Failed to converge after %d iterations, value is %s."
  323. % (itr + 1, p))
  324. raise RuntimeError(msg)
  325. return _results_select(full_output, (p, funcalls, itr + 1, _ECONVERR))
  326. def _array_newton(func, x0, fprime, args, tol, maxiter, fprime2, full_output):
  327. """
  328. A vectorized version of Newton, Halley, and secant methods for arrays.
  329. Do not use this method directly. This method is called from `newton`
  330. when ``np.size(x0) > 1`` is ``True``. For docstring, see `newton`.
  331. """
  332. # Explicitly copy `x0` as `p` will be modified inplace, but the
  333. # user's array should not be altered.
  334. p = np.array(x0, copy=True)
  335. failures = np.ones_like(p, dtype=bool)
  336. nz_der = np.ones_like(failures)
  337. if fprime is not None:
  338. # Newton-Raphson method
  339. for iteration in range(maxiter):
  340. # first evaluate fval
  341. fval = np.asarray(func(p, *args))
  342. # If all fval are 0, all roots have been found, then terminate
  343. if not fval.any():
  344. failures = fval.astype(bool)
  345. break
  346. fder = np.asarray(fprime(p, *args))
  347. nz_der = (fder != 0)
  348. # stop iterating if all derivatives are zero
  349. if not nz_der.any():
  350. break
  351. # Newton step
  352. dp = fval[nz_der] / fder[nz_der]
  353. if fprime2 is not None:
  354. fder2 = np.asarray(fprime2(p, *args))
  355. dp = dp / (1.0 - 0.5 * dp * fder2[nz_der] / fder[nz_der])
  356. # only update nonzero derivatives
  357. p = np.asarray(p, dtype=np.result_type(p, dp, np.float64))
  358. p[nz_der] -= dp
  359. failures[nz_der] = np.abs(dp) >= tol # items not yet converged
  360. # stop iterating if there aren't any failures, not incl zero der
  361. if not failures[nz_der].any():
  362. break
  363. else:
  364. # Secant method
  365. dx = np.finfo(float).eps**0.33
  366. p1 = p * (1 + dx) + np.where(p >= 0, dx, -dx)
  367. q0 = np.asarray(func(p, *args))
  368. q1 = np.asarray(func(p1, *args))
  369. active = np.ones_like(p, dtype=bool)
  370. for iteration in range(maxiter):
  371. nz_der = (q1 != q0)
  372. # stop iterating if all derivatives are zero
  373. if not nz_der.any():
  374. p = (p1 + p) / 2.0
  375. break
  376. # Secant Step
  377. dp = (q1 * (p1 - p))[nz_der] / (q1 - q0)[nz_der]
  378. # only update nonzero derivatives
  379. p = np.asarray(p, dtype=np.result_type(p, p1, dp, np.float64))
  380. p[nz_der] = p1[nz_der] - dp
  381. active_zero_der = ~nz_der & active
  382. p[active_zero_der] = (p1 + p)[active_zero_der] / 2.0
  383. active &= nz_der # don't assign zero derivatives again
  384. failures[nz_der] = np.abs(dp) >= tol # not yet converged
  385. # stop iterating if there aren't any failures, not incl zero der
  386. if not failures[nz_der].any():
  387. break
  388. p1, p = p, p1
  389. q0 = q1
  390. q1 = np.asarray(func(p1, *args))
  391. zero_der = ~nz_der & failures # don't include converged with zero-ders
  392. if zero_der.any():
  393. # Secant warnings
  394. if fprime is None:
  395. nonzero_dp = (p1 != p)
  396. # non-zero dp, but infinite newton step
  397. zero_der_nz_dp = (zero_der & nonzero_dp)
  398. if zero_der_nz_dp.any():
  399. rms = np.sqrt(
  400. sum((p1[zero_der_nz_dp] - p[zero_der_nz_dp]) ** 2)
  401. )
  402. warnings.warn(
  403. 'RMS of {:g} reached'.format(rms), RuntimeWarning)
  404. # Newton or Halley warnings
  405. else:
  406. all_or_some = 'all' if zero_der.all() else 'some'
  407. msg = '{:s} derivatives were zero'.format(all_or_some)
  408. warnings.warn(msg, RuntimeWarning)
  409. elif failures.any():
  410. all_or_some = 'all' if failures.all() else 'some'
  411. msg = '{0:s} failed to converge after {1:d} iterations'.format(
  412. all_or_some, maxiter
  413. )
  414. if failures.all():
  415. raise RuntimeError(msg)
  416. warnings.warn(msg, RuntimeWarning)
  417. if full_output:
  418. result = namedtuple('result', ('root', 'converged', 'zero_der'))
  419. p = result(p, ~failures, zero_der)
  420. return p
  421. def bisect(f, a, b, args=(),
  422. xtol=_xtol, rtol=_rtol, maxiter=_iter,
  423. full_output=False, disp=True):
  424. """
  425. Find root of a function within an interval using bisection.
  426. Basic bisection routine to find a zero of the function `f` between the
  427. arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs.
  428. Slow but sure.
  429. Parameters
  430. ----------
  431. f : function
  432. Python function returning a number. `f` must be continuous, and
  433. f(a) and f(b) must have opposite signs.
  434. a : scalar
  435. One end of the bracketing interval [a,b].
  436. b : scalar
  437. The other end of the bracketing interval [a,b].
  438. xtol : number, optional
  439. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  440. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  441. parameter must be nonnegative.
  442. rtol : number, optional
  443. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  444. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  445. parameter cannot be smaller than its default value of
  446. ``4*np.finfo(float).eps``.
  447. maxiter : int, optional
  448. If convergence is not achieved in `maxiter` iterations, an error is
  449. raised. Must be >= 0.
  450. args : tuple, optional
  451. Containing extra arguments for the function `f`.
  452. `f` is called by ``apply(f, (x)+args)``.
  453. full_output : bool, optional
  454. If `full_output` is False, the root is returned. If `full_output` is
  455. True, the return value is ``(x, r)``, where x is the root, and r is
  456. a `RootResults` object.
  457. disp : bool, optional
  458. If True, raise RuntimeError if the algorithm didn't converge.
  459. Otherwise, the convergence status is recorded in a `RootResults`
  460. return object.
  461. Returns
  462. -------
  463. x0 : float
  464. Zero of `f` between `a` and `b`.
  465. r : `RootResults` (present if ``full_output = True``)
  466. Object containing information about the convergence. In particular,
  467. ``r.converged`` is True if the routine converged.
  468. Examples
  469. --------
  470. >>> def f(x):
  471. ... return (x**2 - 1)
  472. >>> from scipy import optimize
  473. >>> root = optimize.bisect(f, 0, 2)
  474. >>> root
  475. 1.0
  476. >>> root = optimize.bisect(f, -2, 0)
  477. >>> root
  478. -1.0
  479. See Also
  480. --------
  481. brentq, brenth, bisect, newton
  482. fixed_point : scalar fixed-point finder
  483. fsolve : n-dimensional root-finding
  484. """
  485. if not isinstance(args, tuple):
  486. args = (args,)
  487. maxiter = operator.index(maxiter)
  488. if xtol <= 0:
  489. raise ValueError("xtol too small (%g <= 0)" % xtol)
  490. if rtol < _rtol:
  491. raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
  492. r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
  493. return results_c(full_output, r)
  494. def ridder(f, a, b, args=(),
  495. xtol=_xtol, rtol=_rtol, maxiter=_iter,
  496. full_output=False, disp=True):
  497. """
  498. Find a root of a function in an interval using Ridder's method.
  499. Parameters
  500. ----------
  501. f : function
  502. Python function returning a number. f must be continuous, and f(a) and
  503. f(b) must have opposite signs.
  504. a : scalar
  505. One end of the bracketing interval [a,b].
  506. b : scalar
  507. The other end of the bracketing interval [a,b].
  508. xtol : number, optional
  509. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  510. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  511. parameter must be nonnegative.
  512. rtol : number, optional
  513. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  514. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  515. parameter cannot be smaller than its default value of
  516. ``4*np.finfo(float).eps``.
  517. maxiter : int, optional
  518. If convergence is not achieved in `maxiter` iterations, an error is
  519. raised. Must be >= 0.
  520. args : tuple, optional
  521. Containing extra arguments for the function `f`.
  522. `f` is called by ``apply(f, (x)+args)``.
  523. full_output : bool, optional
  524. If `full_output` is False, the root is returned. If `full_output` is
  525. True, the return value is ``(x, r)``, where `x` is the root, and `r` is
  526. a `RootResults` object.
  527. disp : bool, optional
  528. If True, raise RuntimeError if the algorithm didn't converge.
  529. Otherwise, the convergence status is recorded in any `RootResults`
  530. return object.
  531. Returns
  532. -------
  533. x0 : float
  534. Zero of `f` between `a` and `b`.
  535. r : `RootResults` (present if ``full_output = True``)
  536. Object containing information about the convergence.
  537. In particular, ``r.converged`` is True if the routine converged.
  538. See Also
  539. --------
  540. brentq, brenth, bisect, newton : 1-D root-finding
  541. fixed_point : scalar fixed-point finder
  542. Notes
  543. -----
  544. Uses [Ridders1979]_ method to find a zero of the function `f` between the
  545. arguments `a` and `b`. Ridders' method is faster than bisection, but not
  546. generally as fast as the Brent routines. [Ridders1979]_ provides the
  547. classic description and source of the algorithm. A description can also be
  548. found in any recent edition of Numerical Recipes.
  549. The routine used here diverges slightly from standard presentations in
  550. order to be a bit more careful of tolerance.
  551. References
  552. ----------
  553. .. [Ridders1979]
  554. Ridders, C. F. J. "A New Algorithm for Computing a
  555. Single Root of a Real Continuous Function."
  556. IEEE Trans. Circuits Systems 26, 979-980, 1979.
  557. Examples
  558. --------
  559. >>> def f(x):
  560. ... return (x**2 - 1)
  561. >>> from scipy import optimize
  562. >>> root = optimize.ridder(f, 0, 2)
  563. >>> root
  564. 1.0
  565. >>> root = optimize.ridder(f, -2, 0)
  566. >>> root
  567. -1.0
  568. """
  569. if not isinstance(args, tuple):
  570. args = (args,)
  571. maxiter = operator.index(maxiter)
  572. if xtol <= 0:
  573. raise ValueError("xtol too small (%g <= 0)" % xtol)
  574. if rtol < _rtol:
  575. raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
  576. r = _zeros._ridder(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
  577. return results_c(full_output, r)
  578. def brentq(f, a, b, args=(),
  579. xtol=_xtol, rtol=_rtol, maxiter=_iter,
  580. full_output=False, disp=True):
  581. """
  582. Find a root of a function in a bracketing interval using Brent's method.
  583. Uses the classic Brent's method to find a zero of the function `f` on
  584. the sign changing interval [a , b]. Generally considered the best of the
  585. rootfinding routines here. It is a safe version of the secant method that
  586. uses inverse quadratic extrapolation. Brent's method combines root
  587. bracketing, interval bisection, and inverse quadratic interpolation. It is
  588. sometimes known as the van Wijngaarden-Dekker-Brent method. Brent (1973)
  589. claims convergence is guaranteed for functions computable within [a,b].
  590. [Brent1973]_ provides the classic description of the algorithm. Another
  591. description can be found in a recent edition of Numerical Recipes, including
  592. [PressEtal1992]_. A third description is at
  593. http://mathworld.wolfram.com/BrentsMethod.html. It should be easy to
  594. understand the algorithm just by reading our code. Our code diverges a bit
  595. from standard presentations: we choose a different formula for the
  596. extrapolation step.
  597. Parameters
  598. ----------
  599. f : function
  600. Python function returning a number. The function :math:`f`
  601. must be continuous, and :math:`f(a)` and :math:`f(b)` must
  602. have opposite signs.
  603. a : scalar
  604. One end of the bracketing interval :math:`[a, b]`.
  605. b : scalar
  606. The other end of the bracketing interval :math:`[a, b]`.
  607. xtol : number, optional
  608. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  609. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  610. parameter must be nonnegative. For nice functions, Brent's
  611. method will often satisfy the above condition with ``xtol/2``
  612. and ``rtol/2``. [Brent1973]_
  613. rtol : number, optional
  614. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  615. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  616. parameter cannot be smaller than its default value of
  617. ``4*np.finfo(float).eps``. For nice functions, Brent's
  618. method will often satisfy the above condition with ``xtol/2``
  619. and ``rtol/2``. [Brent1973]_
  620. maxiter : int, optional
  621. If convergence is not achieved in `maxiter` iterations, an error is
  622. raised. Must be >= 0.
  623. args : tuple, optional
  624. Containing extra arguments for the function `f`.
  625. `f` is called by ``apply(f, (x)+args)``.
  626. full_output : bool, optional
  627. If `full_output` is False, the root is returned. If `full_output` is
  628. True, the return value is ``(x, r)``, where `x` is the root, and `r` is
  629. a `RootResults` object.
  630. disp : bool, optional
  631. If True, raise RuntimeError if the algorithm didn't converge.
  632. Otherwise, the convergence status is recorded in any `RootResults`
  633. return object.
  634. Returns
  635. -------
  636. x0 : float
  637. Zero of `f` between `a` and `b`.
  638. r : `RootResults` (present if ``full_output = True``)
  639. Object containing information about the convergence. In particular,
  640. ``r.converged`` is True if the routine converged.
  641. Notes
  642. -----
  643. `f` must be continuous. f(a) and f(b) must have opposite signs.
  644. Related functions fall into several classes:
  645. multivariate local optimizers
  646. `fmin`, `fmin_powell`, `fmin_cg`, `fmin_bfgs`, `fmin_ncg`
  647. nonlinear least squares minimizer
  648. `leastsq`
  649. constrained multivariate optimizers
  650. `fmin_l_bfgs_b`, `fmin_tnc`, `fmin_cobyla`
  651. global optimizers
  652. `basinhopping`, `brute`, `differential_evolution`
  653. local scalar minimizers
  654. `fminbound`, `brent`, `golden`, `bracket`
  655. N-D root-finding
  656. `fsolve`
  657. 1-D root-finding
  658. `brenth`, `ridder`, `bisect`, `newton`
  659. scalar fixed-point finder
  660. `fixed_point`
  661. References
  662. ----------
  663. .. [Brent1973]
  664. Brent, R. P.,
  665. *Algorithms for Minimization Without Derivatives*.
  666. Englewood Cliffs, NJ: Prentice-Hall, 1973. Ch. 3-4.
  667. .. [PressEtal1992]
  668. Press, W. H.; Flannery, B. P.; Teukolsky, S. A.; and Vetterling, W. T.
  669. *Numerical Recipes in FORTRAN: The Art of Scientific Computing*, 2nd ed.
  670. Cambridge, England: Cambridge University Press, pp. 352-355, 1992.
  671. Section 9.3: "Van Wijngaarden-Dekker-Brent Method."
  672. Examples
  673. --------
  674. >>> def f(x):
  675. ... return (x**2 - 1)
  676. >>> from scipy import optimize
  677. >>> root = optimize.brentq(f, -2, 0)
  678. >>> root
  679. -1.0
  680. >>> root = optimize.brentq(f, 0, 2)
  681. >>> root
  682. 1.0
  683. """
  684. if not isinstance(args, tuple):
  685. args = (args,)
  686. maxiter = operator.index(maxiter)
  687. if xtol <= 0:
  688. raise ValueError("xtol too small (%g <= 0)" % xtol)
  689. if rtol < _rtol:
  690. raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
  691. r = _zeros._brentq(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
  692. return results_c(full_output, r)
  693. def brenth(f, a, b, args=(),
  694. xtol=_xtol, rtol=_rtol, maxiter=_iter,
  695. full_output=False, disp=True):
  696. """Find a root of a function in a bracketing interval using Brent's
  697. method with hyperbolic extrapolation.
  698. A variation on the classic Brent routine to find a zero of the function f
  699. between the arguments a and b that uses hyperbolic extrapolation instead of
  700. inverse quadratic extrapolation. Bus & Dekker (1975) guarantee convergence
  701. for this method, claiming that the upper bound of function evaluations here
  702. is 4 or 5 times lesser than that for bisection.
  703. f(a) and f(b) cannot have the same signs. Generally, on a par with the
  704. brent routine, but not as heavily tested. It is a safe version of the
  705. secant method that uses hyperbolic extrapolation.
  706. The version here is by Chuck Harris, and implements Algorithm M of
  707. [BusAndDekker1975]_, where further details (convergence properties,
  708. additional remarks and such) can be found
  709. Parameters
  710. ----------
  711. f : function
  712. Python function returning a number. f must be continuous, and f(a) and
  713. f(b) must have opposite signs.
  714. a : scalar
  715. One end of the bracketing interval [a,b].
  716. b : scalar
  717. The other end of the bracketing interval [a,b].
  718. xtol : number, optional
  719. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  720. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  721. parameter must be nonnegative. As with `brentq`, for nice
  722. functions the method will often satisfy the above condition
  723. with ``xtol/2`` and ``rtol/2``.
  724. rtol : number, optional
  725. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  726. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  727. parameter cannot be smaller than its default value of
  728. ``4*np.finfo(float).eps``. As with `brentq`, for nice functions
  729. the method will often satisfy the above condition with
  730. ``xtol/2`` and ``rtol/2``.
  731. maxiter : int, optional
  732. If convergence is not achieved in `maxiter` iterations, an error is
  733. raised. Must be >= 0.
  734. args : tuple, optional
  735. Containing extra arguments for the function `f`.
  736. `f` is called by ``apply(f, (x)+args)``.
  737. full_output : bool, optional
  738. If `full_output` is False, the root is returned. If `full_output` is
  739. True, the return value is ``(x, r)``, where `x` is the root, and `r` is
  740. a `RootResults` object.
  741. disp : bool, optional
  742. If True, raise RuntimeError if the algorithm didn't converge.
  743. Otherwise, the convergence status is recorded in any `RootResults`
  744. return object.
  745. Returns
  746. -------
  747. x0 : float
  748. Zero of `f` between `a` and `b`.
  749. r : `RootResults` (present if ``full_output = True``)
  750. Object containing information about the convergence. In particular,
  751. ``r.converged`` is True if the routine converged.
  752. See Also
  753. --------
  754. fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers
  755. leastsq : nonlinear least squares minimizer
  756. fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers
  757. basinhopping, differential_evolution, brute : global optimizers
  758. fminbound, brent, golden, bracket : local scalar minimizers
  759. fsolve : N-D root-finding
  760. brentq, brenth, ridder, bisect, newton : 1-D root-finding
  761. fixed_point : scalar fixed-point finder
  762. References
  763. ----------
  764. .. [BusAndDekker1975]
  765. Bus, J. C. P., Dekker, T. J.,
  766. "Two Efficient Algorithms with Guaranteed Convergence for Finding a Zero
  767. of a Function", ACM Transactions on Mathematical Software, Vol. 1, Issue
  768. 4, Dec. 1975, pp. 330-345. Section 3: "Algorithm M".
  769. :doi:`10.1145/355656.355659`
  770. Examples
  771. --------
  772. >>> def f(x):
  773. ... return (x**2 - 1)
  774. >>> from scipy import optimize
  775. >>> root = optimize.brenth(f, -2, 0)
  776. >>> root
  777. -1.0
  778. >>> root = optimize.brenth(f, 0, 2)
  779. >>> root
  780. 1.0
  781. """
  782. if not isinstance(args, tuple):
  783. args = (args,)
  784. maxiter = operator.index(maxiter)
  785. if xtol <= 0:
  786. raise ValueError("xtol too small (%g <= 0)" % xtol)
  787. if rtol < _rtol:
  788. raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
  789. r = _zeros._brenth(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
  790. return results_c(full_output, r)
  791. ################################
  792. # TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions", by
  793. # Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
  794. # See [1]
  795. def _notclose(fs, rtol=_rtol, atol=_xtol):
  796. # Ensure not None, not 0, all finite, and not very close to each other
  797. notclosefvals = (
  798. all(fs) and all(np.isfinite(fs)) and
  799. not any(any(np.isclose(_f, fs[i + 1:], rtol=rtol, atol=atol))
  800. for i, _f in enumerate(fs[:-1])))
  801. return notclosefvals
  802. def _secant(xvals, fvals):
  803. """Perform a secant step, taking a little care"""
  804. # Secant has many "mathematically" equivalent formulations
  805. # x2 = x0 - (x1 - x0)/(f1 - f0) * f0
  806. # = x1 - (x1 - x0)/(f1 - f0) * f1
  807. # = (-x1 * f0 + x0 * f1) / (f1 - f0)
  808. # = (-f0 / f1 * x1 + x0) / (1 - f0 / f1)
  809. # = (-f1 / f0 * x0 + x1) / (1 - f1 / f0)
  810. x0, x1 = xvals[:2]
  811. f0, f1 = fvals[:2]
  812. if f0 == f1:
  813. return np.nan
  814. if np.abs(f1) > np.abs(f0):
  815. x2 = (-f0 / f1 * x1 + x0) / (1 - f0 / f1)
  816. else:
  817. x2 = (-f1 / f0 * x0 + x1) / (1 - f1 / f0)
  818. return x2
  819. def _update_bracket(ab, fab, c, fc):
  820. """Update a bracket given (c, fc), return the discarded endpoints."""
  821. fa, fb = fab
  822. idx = (0 if np.sign(fa) * np.sign(fc) > 0 else 1)
  823. rx, rfx = ab[idx], fab[idx]
  824. fab[idx] = fc
  825. ab[idx] = c
  826. return rx, rfx
  827. def _compute_divided_differences(xvals, fvals, N=None, full=True,
  828. forward=True):
  829. """Return a matrix of divided differences for the xvals, fvals pairs
  830. DD[i, j] = f[x_{i-j}, ..., x_i] for 0 <= j <= i
  831. If full is False, just return the main diagonal(or last row):
  832. f[a], f[a, b] and f[a, b, c].
  833. If forward is False, return f[c], f[b, c], f[a, b, c]."""
  834. if full:
  835. if forward:
  836. xvals = np.asarray(xvals)
  837. else:
  838. xvals = np.array(xvals)[::-1]
  839. M = len(xvals)
  840. N = M if N is None else min(N, M)
  841. DD = np.zeros([M, N])
  842. DD[:, 0] = fvals[:]
  843. for i in range(1, N):
  844. DD[i:, i] = (np.diff(DD[i - 1:, i - 1]) /
  845. (xvals[i:] - xvals[:M - i]))
  846. return DD
  847. xvals = np.asarray(xvals)
  848. dd = np.array(fvals)
  849. row = np.array(fvals)
  850. idx2Use = (0 if forward else -1)
  851. dd[0] = fvals[idx2Use]
  852. for i in range(1, len(xvals)):
  853. denom = xvals[i:i + len(row) - 1] - xvals[:len(row) - 1]
  854. row = np.diff(row)[:] / denom
  855. dd[i] = row[idx2Use]
  856. return dd
  857. def _interpolated_poly(xvals, fvals, x):
  858. """Compute p(x) for the polynomial passing through the specified locations.
  859. Use Neville's algorithm to compute p(x) where p is the minimal degree
  860. polynomial passing through the points xvals, fvals"""
  861. xvals = np.asarray(xvals)
  862. N = len(xvals)
  863. Q = np.zeros([N, N])
  864. D = np.zeros([N, N])
  865. Q[:, 0] = fvals[:]
  866. D[:, 0] = fvals[:]
  867. for k in range(1, N):
  868. alpha = D[k:, k - 1] - Q[k - 1:N - 1, k - 1]
  869. diffik = xvals[0:N - k] - xvals[k:N]
  870. Q[k:, k] = (xvals[k:] - x) / diffik * alpha
  871. D[k:, k] = (xvals[:N - k] - x) / diffik * alpha
  872. # Expect Q[-1, 1:] to be small relative to Q[-1, 0] as x approaches a root
  873. return np.sum(Q[-1, 1:]) + Q[-1, 0]
  874. def _inverse_poly_zero(a, b, c, d, fa, fb, fc, fd):
  875. """Inverse cubic interpolation f-values -> x-values
  876. Given four points (fa, a), (fb, b), (fc, c), (fd, d) with
  877. fa, fb, fc, fd all distinct, find poly IP(y) through the 4 points
  878. and compute x=IP(0).
  879. """
  880. return _interpolated_poly([fa, fb, fc, fd], [a, b, c, d], 0)
  881. def _newton_quadratic(ab, fab, d, fd, k):
  882. """Apply Newton-Raphson like steps, using divided differences to approximate f'
  883. ab is a real interval [a, b] containing a root,
  884. fab holds the real values of f(a), f(b)
  885. d is a real number outside [ab, b]
  886. k is the number of steps to apply
  887. """
  888. a, b = ab
  889. fa, fb = fab
  890. _, B, A = _compute_divided_differences([a, b, d], [fa, fb, fd],
  891. forward=True, full=False)
  892. # _P is the quadratic polynomial through the 3 points
  893. def _P(x):
  894. # Horner evaluation of fa + B * (x - a) + A * (x - a) * (x - b)
  895. return (A * (x - b) + B) * (x - a) + fa
  896. if A == 0:
  897. r = a - fa / B
  898. else:
  899. r = (a if np.sign(A) * np.sign(fa) > 0 else b)
  900. # Apply k Newton-Raphson steps to _P(x), starting from x=r
  901. for i in range(k):
  902. r1 = r - _P(r) / (B + A * (2 * r - a - b))
  903. if not (ab[0] < r1 < ab[1]):
  904. if (ab[0] < r < ab[1]):
  905. return r
  906. r = sum(ab) / 2.0
  907. break
  908. r = r1
  909. return r
  910. class TOMS748Solver:
  911. """Solve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi.
  912. """
  913. _MU = 0.5
  914. _K_MIN = 1
  915. _K_MAX = 100 # A very high value for real usage. Expect 1, 2, maybe 3.
  916. def __init__(self):
  917. self.f = None
  918. self.args = None
  919. self.function_calls = 0
  920. self.iterations = 0
  921. self.k = 2
  922. # ab=[a,b] is a global interval containing a root
  923. self.ab = [np.nan, np.nan]
  924. # fab is function values at a, b
  925. self.fab = [np.nan, np.nan]
  926. self.d = None
  927. self.fd = None
  928. self.e = None
  929. self.fe = None
  930. self.disp = False
  931. self.xtol = _xtol
  932. self.rtol = _rtol
  933. self.maxiter = _iter
  934. def configure(self, xtol, rtol, maxiter, disp, k):
  935. self.disp = disp
  936. self.xtol = xtol
  937. self.rtol = rtol
  938. self.maxiter = maxiter
  939. # Silently replace a low value of k with 1
  940. self.k = max(k, self._K_MIN)
  941. # Noisily replace a high value of k with self._K_MAX
  942. if self.k > self._K_MAX:
  943. msg = "toms748: Overriding k: ->%d" % self._K_MAX
  944. warnings.warn(msg, RuntimeWarning)
  945. self.k = self._K_MAX
  946. def _callf(self, x, error=True):
  947. """Call the user-supplied function, update book-keeping"""
  948. fx = self.f(x, *self.args)
  949. self.function_calls += 1
  950. if not np.isfinite(fx) and error:
  951. raise ValueError("Invalid function value: f(%f) -> %s " % (x, fx))
  952. return fx
  953. def get_result(self, x, flag=_ECONVERGED):
  954. r"""Package the result and statistics into a tuple."""
  955. return (x, self.function_calls, self.iterations, flag)
  956. def _update_bracket(self, c, fc):
  957. return _update_bracket(self.ab, self.fab, c, fc)
  958. def start(self, f, a, b, args=()):
  959. r"""Prepare for the iterations."""
  960. self.function_calls = 0
  961. self.iterations = 0
  962. self.f = f
  963. self.args = args
  964. self.ab[:] = [a, b]
  965. if not np.isfinite(a) or np.imag(a) != 0:
  966. raise ValueError("Invalid x value: %s " % (a))
  967. if not np.isfinite(b) or np.imag(b) != 0:
  968. raise ValueError("Invalid x value: %s " % (b))
  969. fa = self._callf(a)
  970. if not np.isfinite(fa) or np.imag(fa) != 0:
  971. raise ValueError("Invalid function value: f(%f) -> %s " % (a, fa))
  972. if fa == 0:
  973. return _ECONVERGED, a
  974. fb = self._callf(b)
  975. if not np.isfinite(fb) or np.imag(fb) != 0:
  976. raise ValueError("Invalid function value: f(%f) -> %s " % (b, fb))
  977. if fb == 0:
  978. return _ECONVERGED, b
  979. if np.sign(fb) * np.sign(fa) > 0:
  980. raise ValueError("a, b must bracket a root f(%e)=%e, f(%e)=%e " %
  981. (a, fa, b, fb))
  982. self.fab[:] = [fa, fb]
  983. return _EINPROGRESS, sum(self.ab) / 2.0
  984. def get_status(self):
  985. """Determine the current status."""
  986. a, b = self.ab[:2]
  987. if np.isclose(a, b, rtol=self.rtol, atol=self.xtol):
  988. return _ECONVERGED, sum(self.ab) / 2.0
  989. if self.iterations >= self.maxiter:
  990. return _ECONVERR, sum(self.ab) / 2.0
  991. return _EINPROGRESS, sum(self.ab) / 2.0
  992. def iterate(self):
  993. """Perform one step in the algorithm.
  994. Implements Algorithm 4.1(k=1) or 4.2(k=2) in [APS1995]
  995. """
  996. self.iterations += 1
  997. eps = np.finfo(float).eps
  998. d, fd, e, fe = self.d, self.fd, self.e, self.fe
  999. ab_width = self.ab[1] - self.ab[0] # Need the start width below
  1000. c = None
  1001. for nsteps in range(2, self.k+2):
  1002. # If the f-values are sufficiently separated, perform an inverse
  1003. # polynomial interpolation step. Otherwise, nsteps repeats of
  1004. # an approximate Newton-Raphson step.
  1005. if _notclose(self.fab + [fd, fe], rtol=0, atol=32*eps):
  1006. c0 = _inverse_poly_zero(self.ab[0], self.ab[1], d, e,
  1007. self.fab[0], self.fab[1], fd, fe)
  1008. if self.ab[0] < c0 < self.ab[1]:
  1009. c = c0
  1010. if c is None:
  1011. c = _newton_quadratic(self.ab, self.fab, d, fd, nsteps)
  1012. fc = self._callf(c)
  1013. if fc == 0:
  1014. return _ECONVERGED, c
  1015. # re-bracket
  1016. e, fe = d, fd
  1017. d, fd = self._update_bracket(c, fc)
  1018. # u is the endpoint with the smallest f-value
  1019. uix = (0 if np.abs(self.fab[0]) < np.abs(self.fab[1]) else 1)
  1020. u, fu = self.ab[uix], self.fab[uix]
  1021. _, A = _compute_divided_differences(self.ab, self.fab,
  1022. forward=(uix == 0), full=False)
  1023. c = u - 2 * fu / A
  1024. if np.abs(c - u) > 0.5 * (self.ab[1] - self.ab[0]):
  1025. c = sum(self.ab) / 2.0
  1026. else:
  1027. if np.isclose(c, u, rtol=eps, atol=0):
  1028. # c didn't change (much).
  1029. # Either because the f-values at the endpoints have vastly
  1030. # differing magnitudes, or because the root is very close to
  1031. # that endpoint
  1032. frs = np.frexp(self.fab)[1]
  1033. if frs[uix] < frs[1 - uix] - 50: # Differ by more than 2**50
  1034. c = (31 * self.ab[uix] + self.ab[1 - uix]) / 32
  1035. else:
  1036. # Make a bigger adjustment, about the
  1037. # size of the requested tolerance.
  1038. mm = (1 if uix == 0 else -1)
  1039. adj = mm * np.abs(c) * self.rtol + mm * self.xtol
  1040. c = u + adj
  1041. if not self.ab[0] < c < self.ab[1]:
  1042. c = sum(self.ab) / 2.0
  1043. fc = self._callf(c)
  1044. if fc == 0:
  1045. return _ECONVERGED, c
  1046. e, fe = d, fd
  1047. d, fd = self._update_bracket(c, fc)
  1048. # If the width of the new interval did not decrease enough, bisect
  1049. if self.ab[1] - self.ab[0] > self._MU * ab_width:
  1050. e, fe = d, fd
  1051. z = sum(self.ab) / 2.0
  1052. fz = self._callf(z)
  1053. if fz == 0:
  1054. return _ECONVERGED, z
  1055. d, fd = self._update_bracket(z, fz)
  1056. # Record d and e for next iteration
  1057. self.d, self.fd = d, fd
  1058. self.e, self.fe = e, fe
  1059. status, xn = self.get_status()
  1060. return status, xn
  1061. def solve(self, f, a, b, args=(),
  1062. xtol=_xtol, rtol=_rtol, k=2, maxiter=_iter, disp=True):
  1063. r"""Solve f(x) = 0 given an interval containing a zero."""
  1064. self.configure(xtol=xtol, rtol=rtol, maxiter=maxiter, disp=disp, k=k)
  1065. status, xn = self.start(f, a, b, args)
  1066. if status == _ECONVERGED:
  1067. return self.get_result(xn)
  1068. # The first step only has two x-values.
  1069. c = _secant(self.ab, self.fab)
  1070. if not self.ab[0] < c < self.ab[1]:
  1071. c = sum(self.ab) / 2.0
  1072. fc = self._callf(c)
  1073. if fc == 0:
  1074. return self.get_result(c)
  1075. self.d, self.fd = self._update_bracket(c, fc)
  1076. self.e, self.fe = None, None
  1077. self.iterations += 1
  1078. while True:
  1079. status, xn = self.iterate()
  1080. if status == _ECONVERGED:
  1081. return self.get_result(xn)
  1082. if status == _ECONVERR:
  1083. fmt = "Failed to converge after %d iterations, bracket is %s"
  1084. if disp:
  1085. msg = fmt % (self.iterations + 1, self.ab)
  1086. raise RuntimeError(msg)
  1087. return self.get_result(xn, _ECONVERR)
  1088. def toms748(f, a, b, args=(), k=1,
  1089. xtol=_xtol, rtol=_rtol, maxiter=_iter,
  1090. full_output=False, disp=True):
  1091. """
  1092. Find a zero using TOMS Algorithm 748 method.
  1093. Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a
  1094. zero of the function `f` on the interval `[a , b]`, where `f(a)` and
  1095. `f(b)` must have opposite signs.
  1096. It uses a mixture of inverse cubic interpolation and
  1097. "Newton-quadratic" steps. [APS1995].
  1098. Parameters
  1099. ----------
  1100. f : function
  1101. Python function returning a scalar. The function :math:`f`
  1102. must be continuous, and :math:`f(a)` and :math:`f(b)`
  1103. have opposite signs.
  1104. a : scalar,
  1105. lower boundary of the search interval
  1106. b : scalar,
  1107. upper boundary of the search interval
  1108. args : tuple, optional
  1109. containing extra arguments for the function `f`.
  1110. `f` is called by ``f(x, *args)``.
  1111. k : int, optional
  1112. The number of Newton quadratic steps to perform each
  1113. iteration. ``k>=1``.
  1114. xtol : scalar, optional
  1115. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  1116. atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
  1117. parameter must be nonnegative.
  1118. rtol : scalar, optional
  1119. The computed root ``x0`` will satisfy ``np.allclose(x, x0,
  1120. atol=xtol, rtol=rtol)``, where ``x`` is the exact root.
  1121. maxiter : int, optional
  1122. If convergence is not achieved in `maxiter` iterations, an error is
  1123. raised. Must be >= 0.
  1124. full_output : bool, optional
  1125. If `full_output` is False, the root is returned. If `full_output` is
  1126. True, the return value is ``(x, r)``, where `x` is the root, and `r` is
  1127. a `RootResults` object.
  1128. disp : bool, optional
  1129. If True, raise RuntimeError if the algorithm didn't converge.
  1130. Otherwise, the convergence status is recorded in the `RootResults`
  1131. return object.
  1132. Returns
  1133. -------
  1134. x0 : float
  1135. Approximate Zero of `f`
  1136. r : `RootResults` (present if ``full_output = True``)
  1137. Object containing information about the convergence. In particular,
  1138. ``r.converged`` is True if the routine converged.
  1139. See Also
  1140. --------
  1141. brentq, brenth, ridder, bisect, newton
  1142. fsolve : find zeroes in N dimensions.
  1143. Notes
  1144. -----
  1145. `f` must be continuous.
  1146. Algorithm 748 with ``k=2`` is asymptotically the most efficient
  1147. algorithm known for finding roots of a four times continuously
  1148. differentiable function.
  1149. In contrast with Brent's algorithm, which may only decrease the length of
  1150. the enclosing bracket on the last step, Algorithm 748 decreases it each
  1151. iteration with the same asymptotic efficiency as it finds the root.
  1152. For easy statement of efficiency indices, assume that `f` has 4
  1153. continuouous deriviatives.
  1154. For ``k=1``, the convergence order is at least 2.7, and with about
  1155. asymptotically 2 function evaluations per iteration, the efficiency
  1156. index is approximately 1.65.
  1157. For ``k=2``, the order is about 4.6 with asymptotically 3 function
  1158. evaluations per iteration, and the efficiency index 1.66.
  1159. For higher values of `k`, the efficiency index approaches
  1160. the kth root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are
  1161. usually appropriate.
  1162. References
  1163. ----------
  1164. .. [APS1995]
  1165. Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
  1166. *Algorithm 748: Enclosing Zeros of Continuous Functions*,
  1167. ACM Trans. Math. Softw. Volume 221(1995)
  1168. doi = {10.1145/210089.210111}
  1169. Examples
  1170. --------
  1171. >>> def f(x):
  1172. ... return (x**3 - 1) # only one real root at x = 1
  1173. >>> from scipy import optimize
  1174. >>> root, results = optimize.toms748(f, 0, 2, full_output=True)
  1175. >>> root
  1176. 1.0
  1177. >>> results
  1178. converged: True
  1179. flag: 'converged'
  1180. function_calls: 11
  1181. iterations: 5
  1182. root: 1.0
  1183. """
  1184. if xtol <= 0:
  1185. raise ValueError("xtol too small (%g <= 0)" % xtol)
  1186. if rtol < _rtol / 4:
  1187. raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
  1188. maxiter = operator.index(maxiter)
  1189. if maxiter < 1:
  1190. raise ValueError("maxiter must be greater than 0")
  1191. if not np.isfinite(a):
  1192. raise ValueError("a is not finite %s" % a)
  1193. if not np.isfinite(b):
  1194. raise ValueError("b is not finite %s" % b)
  1195. if a >= b:
  1196. raise ValueError("a and b are not an interval [{}, {}]".format(a, b))
  1197. if not k >= 1:
  1198. raise ValueError("k too small (%s < 1)" % k)
  1199. if not isinstance(args, tuple):
  1200. args = (args,)
  1201. solver = TOMS748Solver()
  1202. result = solver.solve(f, a, b, args=args, k=k, xtol=xtol, rtol=rtol,
  1203. maxiter=maxiter, disp=disp)
  1204. x, function_calls, iterations, flag = result
  1205. return _results_select(full_output, (x, function_calls, iterations, flag))