给定精度的浮子范围 [英] Range of floats with a given precision
问题描述
我想创建一个数组,其中包含[0.000,1.000]范围内的所有浮点数,所有浮点数均具有3个小数位/4的精度.
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.
例如
>>> np.arange(start=0.000, stop=1.001, decimals=3)
[0.000, 0.001, ..., 0.100, 0.101, ..., 0.900, ..., 0.999, 0.000]
能做到这一点吗?
推荐答案
您可以使用 np.linspace
:
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. ])
或 np.arange
使用整数然后除法:
or np.arange
using integers and then dividing:
>>> np.arange(0, 1001) / 1000
array([ 0. , 0.001, 0.002, ..., 0.998, 0.999, 1. ])
但是,这实际上不是3位小数,因为所有这些值都是浮点数,并且浮点数不精确.这意味着其中一些数字看起来好像有3个小数,但没有!
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不支持固定的小数,因此为了获得完美的结果",您需要使用Python.例如带有 fractions.Fraction
:
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)]
或 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')]
这篇关于给定精度的浮子范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!