How to: round
Based on the "unexpected behaviour" you are describing, I believe you haven't clear which round operations or the effect they have on numbers or how to format floats as strings.
Let's explore the differences when rounding to n=4
digits different values.
Baseline
We define an array with 13 values (13 just to get some digits), from 0 to 1.
values = np.linspace(0, 1, 13)
The array contains:
array([0. , 0.08333333, 0.16666667, 0.25 , 0.33333333,
0.41666667, 0.5 , 0.58333333, 0.66666667, 0.75 ,
0.83333333, 0.91666667, 1. ])
numpy.around
will increase the value of the n-th figure when the n+1-th is greater or equal to 5
, do nothing otherwise. It is the same as numpy.round
.
np.round(values, n)
>>> array([0. , 0.0833, 0.1667, 0.25 , 0.3333, 0.4167, 0.5 , 0.5833,
0.6667, 0.75 , 0.8333, 0.9167, 1. ])
numpy.ceil
will increase the value of the integer part when there exists digits and drop the digits.
np.ceil(r)
>>> array([0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
numpy.floor
will just drop the digits.
np.floor(r)
>>> array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.])
There are a multitude of ways to format numbers as strings: we will explore some of the more commonly used.
Formatting as floats
To format floats you use the symbol .nf
, where n
is the number of digits you want to leave. It will drop all the following figures and add zeros as padding when required to do so.
[ "{:0.4f}".format(v) for v in r]
>>> ['0.0000', '0.0833', '0.1667', '0.2500', '0.3333', '0.4167', '0.5000',
'0.5833', '0.6667', '0.7500', '0.8333', '0.9167', '1.0000']
Formatting as percentages
To format floats as percentages you use the symbol .n%
, where n
is the number of digits you want to leave, considering that the number will be multiplied by 100
. It will drop all the following figures and add zeros as padding when required to do so.
[ "{:0.4%}".format(v) for v in r]
>>> ['0.0000%', '8.3333%', '16.6667%', '25.0000%', '33.3333%', '41.6667%',
'50.0000%', '58.3333%', '66.6667%', '75.0000%', '83.3333%', '91.6667%',
'100.0000%']
Formatting in scientific notation
To format floats as percentages you use the symbol .ne
, where n
is the number of digits you want to leave, considering that the number will be converted to scientific notation. It will drop all the following figures and add zeros as padding when required to do so, adding at the end the exponent of the number in scientific notation.
[ "{:e}".format(v) for v in r]
>>> [
'0.0000e+00', '8.3333e-02', '1.6667e-01', '2.5000e-01', '3.3333e-01',
'4.1667e-01', '5.0000e-01', '5.8333e-01', '6.6667e-01', '7.5000e-01',
'8.3333e-01', '9.1667e-01', '1.0000e+00'
]
Bonus: formatting complex numbers
Suppose you have a complex number a = 3j+2
: to print its components you would proceed by accessing its attributes:
"The real component is {0.real} and the imaginary one is {0.imag}".format(a)
>>> 'The real component is 2.0 and the imaginary one is 3.0'