The basic problem here is that the Julia parser does not preserve the number of digits that were used when a literal floating-point value was entered.
The only way I can think of to do this is to define a new type of numeric literal that you construct with a string macro. e.g. you could define a type such that:
@test pi ≈ t"3.14"
works, i.e. t"3.14" constructs a type TestNumber(3.14, 0.005) and there is an overloaded isapprox for TestNumber.
I would like to “automatically” get the number of significant digits of a numeric literal.
As @stevengj has shown, that is probably not possible in general without using strings or string macros.
Sorry for not being precise.
Could you give some examples of expected result (negative = false or positive = true)?
I have tried the following examples and I don’t know I can’t understand why one is true and one is false.
julia> pi ≈ t"3.1415"
false
julia> pi ≈ t"3.14159"
true
edit
ok. understood. depends on whether the next digit is less than or greater than 5
Thank you for the suggestion @rocco_sprmnt21 .
Your function captures the idea well. I would prefer it to be symmetric, but that should not be too hard to fix.
Clearly my original post was not precise enough. My main question is if there is already some package (or standard function) that does this.
well … then @steveng’sj solution is right for you, in the absence of a library solution?
maybe something like that if it were available working would be closer to your expectations?
Base.isapprox(x::Number, y::Number, sigdigits:: Bool) =
if sigdigits
# here the expressions you used in
# sigdigs
# and
# aresame
return isapprox(x, y, atol = .49*0.1^(tol_digits))`
end