Reputation: 4545
I want to create an array of all floating point numbers in the range [0.000, 1.000], all with 3 decimal places / precision of 4.
e.g.
>>> np.arange(start=0.000, stop=1.001, decimals=3)
[0.000, 0.001, ..., 0.100, 0.101, ..., 0.900, ..., 0.999, 0.000]
Can something along the lines of this be done?
Upvotes: 5
Views: 6909
Reputation: 152637
You could use np.linspace
:
>>> import numpy as np
>>> np.linspace(0, 1, 1001)
array([ 0. , 0.001, 0.002, ..., 0.998, 0.999, 1. ])
or np.arange
using integers and then dividing:
>>> np.arange(0, 1001) / 1000
array([ 0. , 0.001, 0.002, ..., 0.998, 0.999, 1. ])
However, that's not really 3 decimals because all of these values are floats and floats are inexact. That means some of those numbers may look like they have 3 decimals but they haven't!
>>> '{:.40f}'.format((np.arange(0, 1001) / 1000)[1]) # show 40 decimals of second element
'0.0010000000000000000208166817117216851329'
NumPy doesn't support fixed decimals so in order to get a "perfect result" you need to use Python. For example a list with fractions.Fraction
:
>>> from fractions import Fraction
>>> [Fraction(i, 1000) for i in range(0, 1001)]
[Fraction(0, 1), Fraction(1, 1000), ..., Fraction(999, 1000), Fraction(1, 1)]
or decimal.Decimal
:
>>> from decimal import Decimal
>>> [Decimal(i) / 1000 for i in range(1, 1001)]
[Decimal('0.001'), Decimal('0.002'), ..., Decimal('0.999'), Decimal('1')]
Upvotes: 5