by analog31 · 7y ago · 0 comments
In some cases, rounding is performed for the primary purpose of displaying a number as a string, in which case it can't be any less complicated than the string conversion function itself.
import math
x = 0.49999999999999994
print(x-0.5)
print(math.floor(x+0.5))
I got these printouts: -5.551115123125783e-17
1
So yes, something less than 1/2, with 1/2 added to it, has a floor of 1 in floating point math.Yet another reminder that floating point calculations are approximations, and not exact.
julia> using Benchmarktools
julia> @btime floor(0.49999999999999997+0.5)
0.027 ns (0 allocations: 0 bytes)1.0
julia> @btime floor(0.49999999999999997+BigFloat(0.5))
280.594 ns (6 allocations: 336 bytes)0.0
julia> @code_native floor(0.49999999999999997+BigFloat(0.5))
.text
; ┌ @ floatfuncs.jl:152 within `floor'
subq $24, %rsp
movq %rsi, 16(%rsp)
movq (%rsi), %rax
; │┌ @ floatfuncs.jl:152 within `#floor#543'
movq %rax, (%rsp)
movabsq $jl_system_image_data, %rax
movq %rax, 8(%rsp)
movabsq $japi1_round_16005, %rax
movabsq $jl_system_image_data, %rdi
movq %rsp, %rsi
movl $2, %edx
callq *%rax
; │└
addq $24, %rsp
retq
nopw %cs:(%rax,%rax)
; └
julia> @code_native floor(0.49999999999999997+0.5)
.text
; ┌ @ floatfuncs.jl:152 within `floor'
; │┌ @ floatfuncs.jl:152 within `#floor#543'
; ││┌ @ floatfuncs.jl:152 within `round'
vroundsd $9, %xmm0, %xmm0, %xmm0
; │└└
retq
nopw (%rax,%rax)
; └floating-point calculations are absolutely exact. What's not is conversions between decimals and floating-point.
Are you sure about that? What about 1.00000000000001^2 (using eg 64 bit double)?
Or just explicitly check for 0.5 - 1ulp as a special corner case.