4
$\begingroup$

For a program I write I need some optimal values. I calculated them using Mathematica and I get something like this:

{2375, 2556, 2758, 2974, 3201, 3677, 4173, 5068}

Since my program only accepts specific values like ...

{2000, 2800, 3600, 4200, 5500}

... I will need to round my calculated values to those. That means that every calculated value should be replaced by the closest accepted number.

This is only an example. I calculated more than a hundred values and dont want to round them by myself. How can I use Mathematica to achieve this?

$\endgroup$

1 Answer 1

8
$\begingroup$

Here is one way

data = {2375, 2556, 2758, 2974, 3201, 3677, 4173, 5068};
vals = {2000, 2800, 3600, 4200, 5500};

Nearest[vals, #] & /@ data // Flatten
(* {2000, 2800, 2800, 2800, 3600, 3600, 4200, 5500} *)
$\endgroup$
1
  • $\begingroup$ Easy. Thank you! $\endgroup$
    – Arji
    Aug 20, 2020 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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