2
$\begingroup$

I have a list with its bellow elements:

{-0.7071067811865476, -0.7071067811865475, 0.7071067811865475, 0.7071067811865476}

If I use Union, but there is no change. Because the numbers are different. I want to use of Union for keeping just -0.707 and 0.707 and other digits after third (I mean ...10678....) are not important. How can I apply this aim in Union function. Is there another function for this goal?

$\endgroup$
  • 2
    $\begingroup$ Use Round before or put it as a test in DeleteDuplicates. $\endgroup$ – Kuba Jul 7 '15 at 19:08
  • 5
    $\begingroup$ Union has the option SameTest: Union[list, SameTest -> (Abs[#1 - #2] < 10^-4 &)] $\endgroup$ – Bob Hanlon Jul 7 '15 at 19:16
  • $\begingroup$ With thanks to Kuba, but I think the second comment is more flexible. I have 200 lists, all of them are not similar and if I choose "round" I just have to select a number for rounding which is not useful for other lists $\endgroup$ – Unbelievable Jul 7 '15 at 19:24
  • 3
    $\begingroup$ A comment in favour of rounding: using the SameTest option will slow down Union. Without SameTest, Union relies on sorting, which is of $O(n \log n)$ complexity. SameTest forces comparing each pair, i.e. $O(n^2)$ complexity. $\endgroup$ – Szabolcs Jul 7 '15 at 19:53
  • 1
    $\begingroup$ Alternatively, Sort[Mean /@ FindClusters[list]] $\endgroup$ – Bob Hanlon Jul 8 '15 at 15:22
1
$\begingroup$

Try the following shory code:

DeleteDuplicatesBy[lst,Floor[#,10^-4]&]

Will this help?

$\endgroup$
0
$\begingroup$

Therefore, by all means, study all the answers in the comments assiduously. The Example @Daniel Lichtblau I like most.

But see also:

lst = {-0.7071067811865476, -0.7071067811865475, 0.7071067811865475, 0.7071067811865476}

Rationalize[lst, 0.001]

$\left\{-\frac{29}{41},-\frac{29}{41},\frac{29}{41},\frac{29}{41}\right\}$

DeleteDuplicates[{-(29/41), -(29/41), 29/41, 29/41}]

$\left\{-\frac{29}{41},\frac{29}{41}\right\}$

$\endgroup$
  • $\begingroup$ Will DeleteDuplicatesBy be a better solution? $\endgroup$ – Wjx Jun 27 '16 at 15:24

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.