findRoot <- function(f, a, b, eps=1e-4, maxit=40) {
	fa <- f(a)
	fb <- f(b)
	if (fa * fb >= 0) stop("f(a) * f(b) must be negative")
	root = if (fa < 0) { dx = b - a; a } else { dx = a - b; b }
	for (j in 1:maxit) {
		fmid <- f(xmid <- root + (dx <- dx / 2))
		if (fmid <= 0) root <- xmid
		if (abs(dx) < eps || fmid == 0) return(root)
	}
}

g <- function(x) sin(x^2) - 2 * cos(x)

findRoot(g, -1, 3, eps=1e-6)
