Module: Math
- Defined in:
- lib/regioned_calculation.rb
Class Method Summary collapse
-
.find_root(a, b, precision = 0.01, allow_oob_roots = false, &blk) ⇒ Object
optimized version of find_root, performs 10000 roots’ calculations per sec on Core 2 Duo 2.67.
Class Method Details
.find_root(a, b, precision = 0.01, allow_oob_roots = false, &blk) ⇒ Object
optimized version of find_root, performs 10000 roots’ calculations per sec on Core 2 Duo 2.67
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/regioned_calculation.rb', line 3 def self.find_root(a, b, precision=0.01, allow_oob_roots=false, &blk) fa, fb = yield(a).to_f, yield(b).to_f sa, sb = fa >= 0 ? 1 : -1, fb >= 0 ? 1 : -1 while true do # puts "f(#{a},#{(a/precision).truncate})=#{fa}, f(#{b},#{(b/precision).truncate})=#{fb}" raise "Looking for roots out of bounds" if !allow_oob_roots && sa == sb return a if (a-b).abs < precision || fa.abs <= precision return b if fb.abs <= precision c = (a.to_f + b.to_f) / 2 fc = yield(c) sc = fc >= 0 ? 1 : -1 if sa != sc b, fb, sb = c, fc, sc else a, fa, sa = c, fc, sc end end end |