-1

I would like to create an array of number equally spaced (0.1) between 0.1 and 100

step=0.1
range_a=numpy.arange(step,100+step,step)

why my first element is

range_a[0]
Out[27]: 0.10000000000000001

and not 0.1?

and how do I get an array equal to [0.1, 0.2, 0.3, ..., 100]

gabboshow
  • 5,359
  • 12
  • 48
  • 98
  • 7
    this is related to https://stackoverflow.com/questions/588004/is-floating-point-math-broken basically you're going to get this with floating point representation – EdChum May 14 '18 at 08:07
  • The best you can do is use `decimal` module (but inefficient): `from decimal import Decimal; [Decimal('0.1') * Decimal(int(i)) for i in range(1, int(100/0.1)+1)]`. But *usually* there's no reason why `float` cannot be used. – jpp May 14 '18 at 08:16
  • @Jaco Nope. Both numpy and python use C doubles (almost always 64 bit) as their default floating point values. – FHTMitchell May 14 '18 at 08:23
  • @jpp why did you reopen? I'm tempted to close again. – Jean-François Fabre May 14 '18 at 08:48
  • @Jean-FrançoisFabre, Please do close (I'm not intending to answer). Just OP seems to want *another solution*. But I'm not really sure he wants `decimal`.. So it's not clear what he wants (and why). – jpp May 14 '18 at 08:58

1 Answers1

-3

As mentioned in the comments, this is due to how floats are handled. In general, floats are used for imprecise but quick calculations, and double is used where accuracy is important. Your code can be rewritten as follows to get precisely what you want

step = 0.1
range_a = numpy.arange(step, 100+step, step).astype(numpy.double)
Talha A.
  • 115
  • 5
  • get the same result – gabboshow May 14 '18 at 08:16
  • 2
    @gabboshow And you will get the same result no matter what precision you use because 1/10 cannot be accurately represented in binary. It has a recurring representation, just as 1/3 cannot be accurately represented in decimal. – BoarGules May 14 '18 at 08:20
  • @gabboshow What version of Python are you using? This works in Python 3.6.5 and Python 2.7 as expected. Are you specifying the type of the output with .astype correctly? – Talha A. May 14 '18 at 08:24
  • @TalhaA. That's just the python representation. Assuming this is a 64 bit system, the default numpy float is `np.float64 is np.double`. Your answer (implementation specific) is no better. Another option is `np.longlong` which may be 128 bit but often isn't. In any case, you haven't fixed the fundamental issue of floating point values. – FHTMitchell May 14 '18 at 08:28
  • @TalhaA. it s 3.6.3 – gabboshow May 14 '18 at 08:33