Skip to content

Commit

Permalink
Significant digits REPL representation (#30)
Browse files Browse the repository at this point in the history
shows only significant digits of `Measurement` objects in the REPL.
Relates to #5 as a proof of concept.
  • Loading branch information
BeastyBlacksmith authored and giordano committed Dec 23, 2018
1 parent 0a44e6f commit 3e3263b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.swp
*.jl.cov
*.jl.*.cov
*.jl.mem
Expand Down
26 changes: 26 additions & 0 deletions src/Measurements.jl
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ measurement
# Type representation
Base.show(io::IO, measure::Measurement) =
print(io, measure.val, get(io, :compact, false) ? "±" : " ± ", measure.err)
function Base.show(io::IO, ::MIME"text/plain", m::Measurement )
if get( io, :limit, false )
print(io, round( m.val, digits = -Base.hidigit(m.err, 10) + 2),
get(io, :compact, false) ? "±" : " ± ",
round(m.err, sigdigits=2))
else
print(io, m)
end # if
end

Base.show(io::IO, ::MIME"text/latex", measure::Measurement) =
print(io, "\$", measure.val, " \\pm ", measure.err, "\$")
for mime in (MIME"text/x-tex", MIME"text/x-latex")
Expand All @@ -122,6 +132,22 @@ function Base.show(io::IO, measure::Complex{<:Measurement})
end
print(io, "(", i, ")im")
end
function Base.show(io::IO, mtype::MIME"text/plain", measure::Complex{<:Measurement})
r, i = reim(measure)
compact = get(io, :compact, false)
print(io, "(")
show(io, mtype, r)
print(io, ")")
if signbit(i) && !isnan(i)
i = -i
print(io, compact ? "-" : " - ")
else
print(io, compact ? "+" : " + ")
end
print(io, "(")
show(io, mtype, i)
print(io, ")im")
end
# This is adapted from base/show.jl for Complex type.
function Base.alignment(io::IO, measure::Measurement)
m = match(r"^(.*[])(.*)$", sprint(show, measure, context=io, sizehint=0))
Expand Down
7 changes: 7 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,13 @@ end
end

@testset "Type representation" begin
ww = -0.5345 ± 0.03123
zz = ww * (1 + im)
# test pretty printing at the REPL
@test repr("text/plain", ww, context=IOContext(stdout,:limit=>true,:compact=>true)) == "-0.534±0.031"
@test repr("text/plain", ww, context=:limit=>true) == "-0.534 ± 0.031"
@test repr("text/plain", zz, context=IOContext(stdout,:limit=>true,:compact=>true)) == "(-0.534±0.031)-(0.534±0.031)im"
@test repr("text/plain", zz, context=:limit=>true) == "(-0.534 ± 0.031) - (0.534 ± 0.031)im"
@test repr("text/plain", [w 10x; 100y 1000w]) ==
"2×2 Array{Measurement{Float64},2}:\n -0.5±0.03 30.0±1.0 \n 400.0±20.0 -500.0±30.0"
@test repr("text/plain", complex(x, w)) == "(3.0 ± 0.1) - (0.5 ± 0.03)im"
Expand Down

0 comments on commit 3e3263b

Please sign in to comment.