From: Bruce S. <Bru...@nc...> - 2008-03-30 15:18:50
|
It's nothing more than the fact that floating-point numbers can be represented only approximately in a computer. A simple example from ordinary pencil-and-paper calculations is that 1/3 + 1/3 + 1/3 = 1, but 0.33+0.33+0.33 = .99. If you want arange to produce 0, "1/3", "2/3", but not "1", you should write something like arange(0.0, 1.0-.1, 1.0/3.0). More generally, if you want to go from xi to xf in floating-point increments dx, and not include xf, write arange(xi, xf-0.5*dx, dx). Another solution is something like this, using integers: while n in range(ni, nf, dn): x = scale*n # where scale is a floating-point scale factor .... Bruce Sherwood Frédéric Mantegazza wrote: > On dimanche 30 mars 2008, Joe Heafner wrote: > >> Okay this is driving me crazy. Typing arange(0.1,0.4,0.1) should give >> [0.1, 0.2, 0.3] but instead it gives [0.1, 0.2, 0.3, 0.4]. Typing >> arange(0.1,0.5, 0.1) should give [0.1, 0.2, 0.3, 0.4] and it indeed >> does. Another example that doesn't give the "correct" result is >> arange(0.2,0.8,0.2), which gives [ 0.2, 0.4, 0.6, 0.8]. Is this a bug in >> the arange() code? I've tinkered with this for two days and there seems >> to be no way to predict when arange() will behave as documented. I have >> my students working on a small assignment that uses arange() and I don't >> want this to affect their work. Is there some detail I'm overlooking? > > arange([start,] stop[, step,], dtype=None) > > For integer arguments, just like range() except it returns an array > whose type can be specified by the keyword argument dtype. If dtype > is not specified, the type of the result is deduced from the type of > the arguments. > > For floating point arguments, the length of the result is ceil((stop - > start)/step). This rule may result in the last element of the result > being greater than stop. > > I'm afraid you will have to check the result, and correct it. But I agree, > this is a strange behaviour! > |