bisect: Bisection Method

Description Usage Arguments Details Value Author(s) Examples

View source: R/bisect.R

Description

This function returns the results of binary searching on a monotone increasing function fn.

Usage

1
bisect(fn, lower, upper, discrete = TRUE, target, right = TRUE,index = TRUE,...)

Arguments

fn

a monotone increasing function with numeric/character/logical output. If output is character, the increasing defines as alphabetical order; if it is logical, the increasing defines as order from 'FALSE' to 'TRUE'.

lower

lower bound of the function fn domain.

upper

upper bound of the function fn domain.

discrete

logical; if 'TRUE', the domain is discrete; otherwise, the domain is continuous

target

the target needs to be searched in the range of fn.

right

logical; if 'TRUE', search for the smallest value (right limit for continous domain) of 'x' in the domain of fn such that

fn(x) >= target;

otherwise, search for the largest value (left limit for continous domain) of 'x' in the domain of fn such that such that

fn(x) <= target.

index

logical; if 'TRUE', returns the input value of the fn satisfied the searching condition; otherwise, returns the output value of fn instead.

...

further arguments, see Details

Details

Here are more arguments that are provided by this function:

unit

If the domain is discrete, unit can be used for specified the step length. Default value is '1'.

tol

If the function fn is continous, tol is used for error tolerance. Default value is '10^(-7)'.

For the case one want to apply binary search on a given vector 'arr', a simple way is define:

fn <- function(x) arr[x]

and search on discrete domain c(1,length(arr)) with unit = 1.

Value

If index is 'TRUE', returns a number represents the searching results on domain of fn; else, returns the searching results on range of fn.

Author(s)

Zhicong Zhao

Examples

1
2
3
4
fn <- function(x) if(x>3 && x<5) 4 else x
bisect(fn,0,10,discrete = F,target = 4,right = T) # returns 3 because right limit of f(3) = 4
bisect(fn,0,10,discrete = F,target = 4,right = F) # returns 5 because left limit of f(5) = 4
bisect(fn,0,10,discrete = T,target = 4,right = T) # returns 4 for discrete domain

zhicongz/AnomDetct documentation built on Dec. 12, 2019, 9:16 a.m.