0

I have to change an array with an enumeration. It´s made of 0.0025 steps, but because of a methode I use it changes slightly. So it looks kind of like this:

[0, 0]
[0.002499989, 1]
[0.0049989, 2]
[0.00749989, 3]
[0.0103, 4]

I can´t just round them to the fourth decimal because at the end of the array they get significantly bigger then they should be, so e.g. the last value is 21.1892 instead of 21.1875.

So I tried the following:

def enumeration(data):
 data = np.round_(data[:,0], 4) - (np.round_(data[:,0], 4)%0.0025)
 return data

Whick works fine for all values, except for those who can be devided by 0.0075, so 0.0075, 0.015, 0.0225, etc. Those values get changed to the previous ones, so 0.0075 -> 0.005, 0.015 -> 0.0125, 0.0225 -> 0.02

I have no idea why thats the case, if anybody could explain it to me, that would be great.

vinc00
  • 55
  • 5
  • 4
    "but because of a methode I use it changes slightly..." Maybe you need to fix this at the root instead of after the fact. Is it possible to change this "method" so that it gives the increments you want? Also reference https://stackoverflow.com/questions/588004/is-floating-point-math-broken for an overview of how floating point math works. – Code-Apprentice Feb 16 '23 at 15:13

1 Answers1

0

One solution is to build the list as multiples of 0.0025 directly:

data = np.array([[0.0025*i, i] for i in range(n)])
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268