twBinOptimize

Share:

Description

Finding the index of a sorted numeric vector whose element is closest to target.

Usage

1
2
3
twBinOptimize(x, target = 0, ..., interval = c(1, length(x)), 
    lower = ceiling(min(interval)), upper = floor(max(interval)), 
    maxiter = 100, showiter = FALSE)

Arguments

x

numeric vector to be optimized. The term abs(x[i])-target) is minimized.

target

Target value for x. Defaults to 0.

...

not used

interval

a vector containing the end-points of the interval to be searched for target.

lower

the lower end point of the interval to be searched.

upper

the upper end point of the interval to be searched.

maxiter

Maximum number of search iterations. Defaults to 100.

showiter

Boolean flag indicating whether the algorithm state should be printed at each iteration. Defaults to FALSE.

Details

This function can be applied similar to optimize for cases, where the argument to be optimized is an index instead of a continuous variable. A binary search over the index is performed.
The function x must be monotonic. If it is not strictly monotonic the returned index ($where) can be any of the indices with equal values.
The code is based on binsearch of the gtools package. In difference to the original code, it returns always only one best estimate.

Value

A list containing:

call

How the function was called.

numiter

The number of iterations performed

flag

One of the strings, "Found", "Between Elements", "Maximum number of iterations reached", "Reached lower boundary", or "Reached upper boundary."

where

One or two values indicating where the search terminated.

value

Value of the x at the index of where.

If vector is empty or upper boundary is lower than lower boundary, where and value are NA

Author(s)

Thomas Wutzler

See Also

twBinOptimizeFun, twMisc

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# linear search is faster up with vectors to about 1e4 entries 
x <- exp(seq(-10,100,length.out=1e4))
# with longer vectors, the binary search is superior
x <- exp(seq(-10,100,length.out=1e6))

# generate some sample indices that will be found by optimization
n <- 1e2
.where <- sample.int(length(x),n, replace=TRUE)
.val <- x[.where]*1.00001   # add some error, for exact matches use the faster function match
system.time( .where2 <- sapply(.val, function(vali){ which.min(abs(x-vali))  } ))   
system.time( .where3 <- sapply(.val, function(vali){ twBinOptimize(x,vali)$where} ))
#Rprof();  .numiter3 <- sapply(.val, function(vali){ twBinOptimize(x,vali)$numiter} ); Rprof(NULL); summaryRprof()

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.