Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

""" 

Unified interfaces to root finding algorithms for real or complex 

scalar functions. 

 

Functions 

--------- 

- root : find a root of a scalar function. 

""" 

from __future__ import division, print_function, absolute_import 

 

import numpy as np 

from scipy._lib.six import callable 

 

from . import zeros as optzeros 

 

__all__ = ['root_scalar'] 

 

 

class MemoizeDer(object): 

"""Decorator that caches the value and derivative(s) of function each 

time it is called. 

 

This is a simplistic memoizer that calls and caches a single value 

of `f(x, *args)`. 

It assumes that `args` does not change between invocations. 

It supports the use case of a root-finder where `args` is fixed, 

`x` changes, and only rarely, if at all, does x assume the same value 

more than once.""" 

def __init__(self, fun): 

self.fun = fun 

self.vals = None 

self.x = None 

self.n_calls = 0 

 

def __call__(self, x, *args): 

r"""Calculate f or use cached value if available""" 

# Derivative may be requested before the function itself, always check 

if self.vals is None or x != self.x: 

fg = self.fun(x, *args) 

self.x = x 

self.n_calls += 1 

self.vals = fg[:] 

return self.vals[0] 

 

def fprime(self, x, *args): 

r"""Calculate f' or use a cached value if available""" 

if self.vals is None or x != self.x: 

self(x, *args) 

return self.vals[1] 

 

def fprime2(self, x, *args): 

r"""Calculate f'' or use a cached value if available""" 

if self.vals is None or x != self.x: 

self(x, *args) 

return self.vals[2] 

 

def ncalls(self): 

return self.n_calls 

 

 

def root_scalar(f, args=(), method=None, bracket=None, 

fprime=None, fprime2=None, 

x0=None, x1=None, 

xtol=None, rtol=None, maxiter=None, 

options=None): 

""" 

Find a root of a scalar function. 

 

Parameters 

---------- 

f : callable 

A function to find a root of. 

args : tuple, optional 

Extra arguments passed to the objective function and its derivative(s). 

method : str, optional 

Type of solver. Should be one of 

 

- 'bisect' :ref:`(see here) <optimize.root_scalar-bisect>` 

- 'brentq' :ref:`(see here) <optimize.root_scalar-brentq>` 

- 'brenth' :ref:`(see here) <optimize.root_scalar-brenth>` 

- 'ridder' :ref:`(see here) <optimize.root_scalar-ridder>` 

- 'toms748' :ref:`(see here) <optimize.root_scalar-toms748>` 

- 'newton' :ref:`(see here) <optimize.root_scalar-newton>` 

- 'secant' :ref:`(see here) <optimize.root_scalar-secant>` 

- 'halley' :ref:`(see here) <optimize.root_scalar-halley>` 

 

bracket: A sequence of 2 floats, optional 

An interval bracketing a root. `f(x, *args)` must have different 

signs at the two endpoints. 

x0 : float, optional 

Initial guess. 

x1 : float, optional 

A second guess. 

fprime : bool or callable, optional 

If `fprime` is a boolean and is True, `f` is assumed to return the 

value of the objective function and of the derivative. 

`fprime` can also be a callable returning the derivative of `f`. In 

this case, it must accept the same arguments as `f`. 

fprime2 : bool or callable, optional 

If `fprime2` is a boolean and is True, `f` is assumed to return the 

value of the objective function and of the 

first and second derivatives. 

`fprime2` can also be a callable returning the second derivative of `f`. 

In this case, it must accept the same arguments as `f`. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

options : dict, optional 

A dictionary of solver options. E.g. ``k``, see 

:obj:`show_options()` for details. 

 

Returns 

------- 

sol : RootResults 

The solution represented as a ``RootResults`` object. 

Important attributes are: ``root`` the solution , ``converged`` a 

boolean flag indicating if the algorithm exited successfully and 

``flag`` which describes the cause of the termination. See 

`RootResults` for a description of other attributes. 

 

See also 

-------- 

show_options : Additional options accepted by the solvers 

root : Find a root of a vector function. 

 

Notes 

----- 

This section describes the available solvers that can be selected by the 

'method' parameter. 

 

The default is to use the best method available for the situation 

presented. 

If a bracket is provided, it may use one of the bracketing methods. 

If a derivative and an initial value are specified, it may 

select one of the derivative-based methods. 

If no method is judged applicable, it will raise an Exception. 

 

 

Examples 

-------- 

 

Find the root of a simple cubic 

 

>>> from scipy import optimize 

>>> def f(x): 

... return (x**3 - 1) # only one real root at x = 1 

 

>>> def fprime(x): 

... return 3*x**2 

 

The `brentq` method takes as input a bracket 

 

>>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq') 

>>> sol.root, sol.iterations, sol.function_calls 

(1.0, 10, 11) 

 

The `newton` method takes as input a single point and uses the derivative(s) 

 

>>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton') 

>>> sol.root, sol.iterations, sol.function_calls 

(1.0, 11, 22) 

 

The function can provide the value and derivative(s) in a single call. 

 

>>> def f_p_pp(x): 

... return (x**3 - 1), 3*x**2, 6*x 

 

>>> sol = optimize.root_scalar(f_p_pp, x0=0.2, fprime=True, method='newton') 

>>> sol.root, sol.iterations, sol.function_calls 

(1.0, 11, 11) 

 

>>> sol = optimize.root_scalar(f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley') 

>>> sol.root, sol.iterations, sol.function_calls 

(1.0, 7, 8) 

 

 

""" 

if not isinstance(args, tuple): 

args = (args,) 

 

if options is None: 

options = {} 

 

# fun also returns the derivative(s) 

is_memoized = False 

if fprime2 is not None and not callable(fprime2): 

if bool(fprime2): 

f = MemoizeDer(f) 

is_memoized = True 

fprime2 = f.fprime2 

fprime = f.fprime 

else: 

fprime2 = None 

if fprime is not None and not callable(fprime): 

if bool(fprime): 

f = MemoizeDer(f) 

is_memoized = True 

fprime = f.fprime 

else: 

fprime = None 

 

# respect solver-specific default tolerances - only pass in if actually set 

kwargs = {} 

for k in ['xtol', 'rtol', 'maxiter']: 

v = locals().get(k) 

if v is not None: 

kwargs[k] = v 

 

# Set any solver-specific options 

if options: 

kwargs.update(options) 

# Always request full_output from the underlying method as _root_scalar 

# always returns a RootResults object 

kwargs.update(full_output=True, disp=False) 

 

# Pick a method if not specified. 

# Use the "best" method available for the situation. 

if not method: 

if bracket: 

method = 'brentq' 

elif x0 is not None: 

if fprime: 

if fprime2: 

method = 'halley' 

else: 

method = 'newton' 

else: 

method = 'secant' 

if not method: 

raise ValueError('Unable to select a solver as neither bracket ' 

'nor starting point provided.') 

 

meth = method.lower() 

map2underlying = {'halley': 'newton', 'secant': 'newton'} 

 

try: 

methodc = getattr(optzeros, map2underlying.get(meth, meth)) 

except AttributeError: 

raise ValueError('Unknown solver %s' % meth) 

 

if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']: 

if not isinstance(bracket, (list, tuple, np.ndarray)): 

raise ValueError('Bracket needed for %s' % method) 

 

a, b = bracket[:2] 

r, sol = methodc(f, a, b, args=args, **kwargs) 

elif meth in ['secant']: 

if x0 is None: 

raise ValueError('x0 must not be None for %s' % method) 

if x1 is None: 

raise ValueError('x1 must not be None for %s' % method) 

if 'xtol' in kwargs: 

kwargs['tol'] = kwargs.pop('xtol') 

r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None, 

x1=x1, **kwargs) 

elif meth in ['newton']: 

if x0 is None: 

raise ValueError('x0 must not be None for %s' % method) 

if not fprime: 

raise ValueError('fprime must be specified for %s' % method) 

if 'xtol' in kwargs: 

kwargs['tol'] = kwargs.pop('xtol') 

r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None, 

**kwargs) 

elif meth in ['halley']: 

if x0 is None: 

raise ValueError('x0 must not be None for %s' % method) 

if not fprime: 

raise ValueError('fprime must be specified for %s' % method) 

if not fprime2: 

raise ValueError('fprime2 must be specified for %s' % method) 

if 'xtol' in kwargs: 

kwargs['tol'] = kwargs.pop('xtol') 

r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs) 

else: 

raise ValueError('Unknown solver %s' % method) 

 

if is_memoized: 

# Replace the function_calls count with the memoized count. 

# Avoids double and triple-counting. 

n_calls = f.n_calls 

sol.function_calls = n_calls 

 

return sol 

 

 

def _root_scalar_brentq_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

 

def _root_scalar_brenth_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

def _root_scalar_toms748_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

 

def _root_scalar_secant_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

x0 : float, required 

Initial guess. 

x1 : float, required 

A second guess. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

 

def _root_scalar_newton_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function and its derivative. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

x0 : float, required 

Initial guess. 

fprime : bool or callable, optional 

If `fprime` is a boolean and is True, `f` is assumed to return the 

value of derivative along with the objective function. 

`fprime` can also be a callable returning the derivative of `f`. In 

this case, it must accept the same arguments as `f`. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

 

def _root_scalar_halley_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function and its derivatives. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

x0 : float, required 

Initial guess. 

fprime : bool or callable, required 

If `fprime` is a boolean and is True, `f` is assumed to return the 

value of derivative along with the objective function. 

`fprime` can also be a callable returning the derivative of `f`. In 

this case, it must accept the same arguments as `f`. 

fprime2 : bool or callable, required 

If `fprime2` is a boolean and is True, `f` is assumed to return the 

value of 1st and 2nd derivatives along with the objective function. 

`fprime2` can also be a callable returning the 2nd derivative of `f`. 

In this case, it must accept the same arguments as `f`. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

 

def _root_scalar_ridder_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass 

 

 

def _root_scalar_bisect_doc(): 

r""" 

Options 

------- 

args : tuple, optional 

Extra arguments passed to the objective function. 

xtol : float, optional 

Tolerance (absolute) for termination. 

rtol : float, optional 

Tolerance (relative) for termination. 

maxiter : int, optional 

Maximum number of iterations. 

options: dict, optional 

Specifies any method-specific options not covered above 

 

""" 

pass