5
A = [0.123 0.234 0.562 0.665 ]
B = [0.125 0.225 0.575 0.675]
C = [-43.975 -43.925 -43.875 -43.825 -43.775 -43.725 -43.675]

I would like make array A look like array B. The satellite data I am working with has a 0.05 degree resolution so it's latitude and longitude values are numbered like in array C. So the numbers go up in increments of 0.05 but end in either 25 or 75 as in array C. I have numbers like in array A which I need to match with the grid of the satellite data. I need to round or transform my numbers as in array A to look like those in array B.

I've tried using round and using math.ceil but neither worked fully.

ryyker
  • 22,849
  • 3
  • 43
  • 87
Cristina
  • 53
  • 3
  • I've tried using this function : ```def x_round(x): return math.ceil(x*40)/40```. It works pretty well but I still get values that look like 0.5 or 0.55 and I need them to end in 0.025 or 0.075 – Cristina Nov 14 '19 at 11:24
  • Welcome to Stack Overflow. I infer from your comments that your using python. Is this correct? Could you please post a small sample of your code so we can have a better idea about what is going on? Particularly, show us what you currently obtain and what you would like to. – Yennefer Nov 14 '19 at 12:06
  • 1
    Just a clarification: It appears you are rounding in increments of `0.025`. You have stated clearly you want the numbers to end in `25` or `75`. Are you asking to skip the other increments, such as `00` or `50`. For example, are `0.000`, `0.025`, `0.050` and `0.075` all valid ? – ryyker Nov 14 '19 at 13:22
  • Your description lacks a specific language that you would like to see in any answers, so I have edited tags to include `algorithm` (inviting a more general solution). If this is not correct, edit the tags yourself to include explicitly what you would prefer. – ryyker Nov 14 '19 at 13:35

2 Answers2

1

Here's a rounding algorithm to do that:

  1. Add 0.025
  2. Multiply by 20
  3. Round to the nearest integer
  4. Divide by 20
  5. Subtract 0.025
  6. Round to 3 decimal places (to handle floating point precision issues)

E.g. in python:

def x_round(x): return round((round((x+0.025)*20)/20)-0.025,3);

A = [0.123, 0.234, 0.562, 0.665]

for item in A:
    print(x_round(item))

Output:

0.125
0.225
0.575
0.675

Ergwun
  • 12,579
  • 7
  • 56
  • 83
0

Here's a version that looks for the closest neighbour that ends with 0.025 or 0.075. (Handling negative input is left to the reader.)

JavaScript code:

function f(n){
  n = n * 1000
  let m = n % 100
  if (m <= 50)
    return (n - m + 25) / 1000
  else
    return (n - m + 75) / 1000
}

var A = [0.123, 0.234, 0.562, 0.665]

console.log(JSON.stringify(A))
console.log(JSON.stringify(A.map(x => f(x))))
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61