I have encountered a very bizarre problem. I am trying to create a function that returns an array of values that enclose a range with a certain step size (such as you might find on the axis of a plot). Instead of just using np.arange(min,max,step)
, I want something that rounds the step size better. Here is what I tried:
def get_decade(value):
return pow(10,math.floor(math.log10(value)))
def get_steparray(min,max,delta):
delta_step = float(get_decade(delta))
next = math.floor(min/delta_step)*delta_step
print next
array = [next]
while next < max:
next = int((next+delta_step)/delta_step)*delta_step
print next
array.append(next)
print array
print array
return array
The print statements are in there to help me figure out what is going on. Here is what I tried running it with:
print get_steparray(1.032,1.431,0.1)
From this, I was expecting the array to end up as [1.0,1.1,1.2,1.3,1.4,1.5]
Here is what I get from the function:
1.0
1.1
[1.0, 1.1]
1.2
[1.0, 1.1, 1.2000000000000002]
1.3
[1.0, 1.1, 1.2000000000000002, 1.3]
1.4
[1.0, 1.1, 1.2000000000000002, 1.3, 1.4000000000000001]
1.5
[1.0, 1.1, 1.2000000000000002, 1.3, 1.4000000000000001, 1.5]
[1.0, 1.1, 1.2000000000000002, 1.3, 1.4000000000000001, 1.5]
As you can see, some of them work, and others have the extra decimals added.
Anyone have any ideas what might be causing this? Thanks for any insight you can provide. Alternatively, I would be just as happy if someone knew a better, more functional way to create such an array. Maybe I should just stick to using np.arange and adjust the max/min/step values?
(Yes, I know my code isn't the cleanest. The function above started out much cleaner, but I added some unnecessary features to it to try to get it to work.)
Edit: While I appreciate everyone's insightful comments, I am still not sure that they address my issue fully. As is visible in the printout, each value is stored to sufficient precision of my needs when as an isolated float type. But when they are added to the array, it is only then that they change precision. I am quite aware of the issues with floating points, in general, but was curious about the specific differences between the float and the array. I wonder if maybe the array is storing the value in a lower number of bits than the individual value.
That being said, I think the suggestion to focus more on formatting at the point of usage is what I will end up doing.
Thanks!