Open jzakiya opened 7 years ago
I replacd almost with result and that seemed to fix it, after testing the results compared to other methods.
def inverse_newton_sqrt(n)
raise if n < 0
return Math.sqrt(n).to_i if n < 1 << 53
n_bits = n.bit_length
exp = (n.bit_length - 1) & -2
e_0 = ins_find_initial_exponent(n_bits)
r = ins_find_initial_r(n, e_0)
e_bits, r, x = ins_core(n, e_0, r, exp)
result = r * x >> (e_bits << 1) - (exp >> 1)
#result += 1 if n > almost * almost + (almost << 1)
result += 1 if n > result * result + (result << 1)
result
end
Actually, you can drop the last line too.
def inverse_newton_sqrt(n)
raise if n < 0
return Math.sqrt(n).to_i if n < 1 << 53
n_bits = n.bit_length
exp = (n.bit_length - 1) & -2
e_0 = ins_find_initial_exponent(n_bits)
r = ins_find_initial_r(n, e_0)
e_bits, r, x = ins_core(n, e_0, r, exp)
root = r * x >> (e_bits << 1) - (exp >> 1)
root += 1 if n > root * root + (root << 1)
end
Hey Nathan,
Tried to run updated code benchmarks but it crashes because almost isn't defined/initialized in the inverse_newton_sqrt method.
Also, please include
require 'benchmark/ips'
just before running benchmark code to insure it has been loaded.