Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a number to the nearest 0.05 ending with either a 0.025 or 0.075

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.

like image 680
Cristina Avatar asked Nov 07 '22 12:11

Cristina


1 Answers

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

like image 147
Ergwun Avatar answered Nov 15 '22 07:11

Ergwun