Skip to content

Instantly share code, notes, and snippets.

@Arkoniak
Created January 11, 2017 20:49
Show Gist options
  • Save Arkoniak/56abec14e110688adec5ed857d443685 to your computer and use it in GitHub Desktop.
Save Arkoniak/56abec14e110688adec5ed857d443685 to your computer and use it in GitHub Desktop.
Test format of Float types conversions
# There is no default parse(Float16), this one is taken from
# https://github.com/JuliaLang/julia/issues/16411#issuecomment-256835385
import Base: parse
function parse(::Type{Float16}, str::String)
fp = 0.0
try
fp = parse(Float64, str)
catch
throw(ArgumentError(string("invalid number format \"",str,"\" for Float16")))
end
return convert(Float16, fp)
end
function test_precision(T, n)
vals = Array{Bool}(n)
x = rand(T, n)
for i in 1:n
if T == Float16
x_str = @sprintf("%.4e", x[i])
elseif T == Float32
x_str = @sprintf("%.8e", x[i])
else
x_str = @sprintf("%.16e", x[i])
end
x_num = parse(T, x_str)
vals[i] = x_num == x[i]
end
return all(vals)
end
# All tests are green on my local machine (Julia Version 0.5.0 Commit 3c9d753 (2016-09-19 18:14 UTC))
@assert test_precision(Float16, 10000)
@assert test_precision(Float32, 10000)
@assert test_precision(Float64, 10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment