Skip to content

Instantly share code, notes, and snippets.

@tompng
Created April 16, 2026 16:03
Show Gist options
  • Select an option

  • Save tompng/d0778e492681c8ddec09eda87d198d90 to your computer and use it in GitHub Desktop.

Select an option

Save tompng/d0778e492681c8ddec09eda87d198d90 to your computer and use it in GitHub Desktop.
x = x0 = BigDecimal('1100000000000000087944964434022145632029003198634030825446485394267219165647576318369821312487531766087629873357328440099001976504255934373246955159552')
def to_f(x0)
6.times do |shift|
prec = 27 << shift
exp = 0
x = x0r = x0.mult(1, prec)
[59, 16, 4, 1].each do |bit|
while bit == 1 ? x >= 2**53 : x.exponent - 1 >= (53 + bit)*0.30104
x = x.div(2**bit, prec)
exp += bit
end
end
[59, 16, 4, 1].each do |bit|
while bit == 1 ? x < 2**52 : x.exponent < (53 - bit)*0.30102
x = x.mult(2**bit, prec)
exp -= bit
end
end
d = BigDecimal(1)._decimal_shift(-prec + 20)
if x.frac < 0.5 - d
return [x.to_i, exp, prec]
elsif x.frac > 0.5 + d
return [x.to_i + 1, exp, prec]
elsif shift == 5
xi = x.to_i
return [xi + (x0 < x0r ? 0 : x0 > x0r ? 1 : xi % 2), exp, prec, x0 <=> x0r]
end
end
end
xu = x + 1
xl = x - 1
xu2 = x + BigDecimal('1e-1000')
xl2 = x - BigDecimal('1e-1000')
[xu, xl, xu2, xl2, x].each do
ans = to_f(it)
p [ans, Math.ldexp(ans[0], ans[1]), eval(it.to_s)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment