2
$\begingroup$

Suppose I have a list of numbers, list = {1.25, 4.5, 3.430000, 6.800, 1.250, 8.9, ...}. I would like to construct a function that removes all the numbers with trailing zeros; i.e.,

myFunction[list] = {1.25, 4.5, 8.9, ...}`.

If anyone knows of a way to identify numbers with trailing zeros using pattern matching, then I could just use

DeleteCases[list, <trailing zeros pattern>]

to eliminate them.

$\endgroup$
  • 3
    $\begingroup$ 1.25 has an infinite number of trailing zeros. 3.430000 is probably 3.4300000000001 or so (use InputForm to see this). How many digits do you want to consider? $\endgroup$ – JEM_Mosig Mar 18 '18 at 18:57
2
$\begingroup$

I read this question as asking how to remove a certain class of arbitrary precision numbers from a list. I don't think the OP's answer is robust. I think it will fail on many numbers that one might encounter. So I suggest the following:

hasTrailingZero[n_ /; Head[Precision[n]] === Real] := 
  RealDigits[n][[1, -1]] === 0
hasTrailingZero[___] = False;

The head of Precision[n]] is Real if and only if n is an arbitrary precision real number, so the first definition above is only evaluated for such numbers. This restriction makes hasTrailingZero a robust predicate.

Now I define list as

list = {1.25`3, 4.5`, 3.430000`7, 6.800`4, 1.250`4, 8.9`2, 42, π, 2.50000}

{1.25, 4.5, 3.430000, 6.800, 1.250, 8.9, 42, π, 2.5, ∞, x}

which contains some important additional number forms to test. Both Select or Pick can use hasTrailingZero to delete the numbers that have trailing zeros.

Select[list, Not @* hasTrailingZero]

`{1.25, 4.5, 8.9, 42, π, 2.5, ∞, x}

Pick[list, Not @* hasTrailingZero /@ list]

`{1.25, 4.5, 8.9, 42, π, 2.5, ∞, x}

The item 2.5 remains in the output because, as a machine float, it does not have an internal representation which retains information that Mathematica can use to reconstruct any trailing zeros that may have been entered when the it was typed in.

$\endgroup$
1
$\begingroup$

Though I'm unsure how to implement this exactly, I was able to solve my problem by adding the restriction: If[Last[RealDigits[n][[1]]]] != 0], where n is a decimal number.

$\endgroup$
  • $\begingroup$ I down-voted this answer because it will fail for many possible numbers that n might represent. $\endgroup$ – m_goldberg Mar 18 '18 at 22:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.