clay
clay

Reputation: 20370

Chop or truncate to n significant digits

Julia has a built-in function to round to n significant digits. signif(0.0229, 2) will round to two significant digits and give 0.023.

How can I chop or truncate to n significant digits so that I would get 0.022 instead?

Upvotes: 6

Views: 3827

Answers (3)

Alec
Alec

Reputation: 4472

Note that signif was removed as of Julia 1.0.

However, now Base.round accepts the sigdigits keyword:

julia> round(pi, digits=3)
3.142

julia> round(pi, sigdigits=3)
3.14

The same works for trunc, ceil, and floor.

Source: mforets on Github and @DNF in the comments.


Upvotes: 4

Dan Getz
Dan Getz

Reputation: 18217

Well, not very imaginative. Used @edit signif(0.229,2) to find the source and replace round with floor (and added a Base. for correct Module referencing). Here is the result:

function mysignif(x::Real, digits::Integer, base::Integer=10)
    digits < 1 && throw(DomainError(digits, "`digits` cannot be less than 1."))

    x = float(x)
    (x == 0 || !isfinite(x)) && return x
    og, e = Base._signif_og(x, digits, base)
    if e >= 0 # for numeric stability
        r = trunc(x/og)*og
    else
        r = trunc(x*og)/og
    end
    !isfinite(r) ? x : r
end

Giving:

julia> mysignif(0.0229,2)
0.022

Upvotes: 3

clay
clay

Reputation: 20370

I found a version in Maple and ported to Julia:

function signifChop(num, digits)
    if num == 0.0 then
        return num
    else
        e = ceil(log10(abs(num)))
        scale = 10^(digits - e)
        return trunc(num * scale) / scale
    end
end

# Test cases for signifChop
println("$(signifChop(124.031, 5))")
println("$(signifChop(124.036, 5))")
println("$(signifChop(-124.031, 5))")
println("$(signifChop(-124.036, 5))")
println("$(signifChop(0.00653, 2))")
println("$(signifChop(0.00656, 2))")
println("$(signifChop(-0.00653, 2))")
println("$(signifChop(-0.00656, 2))")

Upvotes: 2

Related Questions