bisection.ijs

Script: ~addons/finance/finexec/toolbox/bisection.ijs
Contributor: William Szuch
Updated: 2022 6 26
Depend: nil
Definitions: loaded to locale base
Status: done
Script source: bisection.ijs

Bisection method of solving: f(x) = 0.
Useful for calculating the money weighted rate of return (mwrr).
Equations:
NF

Definitions

B bisection

bisection (adverb)

Form: explicit
Calculate the solution to the function f(x) = 0 if it
exists is in the range A to B with tolerence TOL
using the Bisection method.
The result is two numbers:
  first number is the approximation for x to the solution f(x) = 0
  second number of the value of f(x) using the approximation ie: error
Some useful steps:
(1) select a suitable tolerence for the function or except default
(2) check if there is a solution - for example using signchange or
    plot
(3) check if there multiple solutions in the range

Syntax

(f)bisection(A;B;[TOL])
f = function to be solved
A,B = lower and upper values of initial range
[TOL] = default tolerence for solution 0.01

Example

 The examples requires:
 load 'plot'
 signchange =: [: - ([: */ ([: * >))       NB. signchange(A,B)
 steps=: {. + (1&{ - {.) * (i.@>: % ])@{:  NB. steps(A,B,N)

   f1 =: _3.12 + [  NB. Simple linear function
   f1 i. 10         NB. shows there is a solution in range 0 to 9
_3.12 _2.12 _1.12 _0.12 0.88 1.88 2.88 3.88 4.88 5.88
   signchange f1(3,5)
1  NB. Sign change in the interval (3,5)

   plot ([;f1) steps(0,10,100)

   (f1)bisection(0;9;0.001)
3.12012 0.000117187
   (f1)bisection(0;9)
3.12891 0.00890625
   (f1)bisection(4;9)
┌──────────────────────────────────┬─┬─┐
│*** No sign change in the range : │4│9│
└──────────────────────────────────┴─┴─┘
 Further examples:
 f2 =: 3 : '_100 + 10 * *: y'
 f3 =: 3 : '100 + _10 * *: y'
 f4 =: 3 : '120 + _10 * *: y'
 plot ([;f2) steps(1,5,10)
 plot ([;f3) steps(1,5,10)
 plot ([;f4) steps(1, 5,10
 (f2)bisection(1;5;0.001)
 (f3)bisection(1;5)
 (f4)bisection(1;5)