0
In [86]: array.std()
Out[86]: 100.70953143681199

In [87]: array.std().round()
Out[87]: 101.0

In [88]: array.std().round(2)
Out[88]: 100.70999999999999

In [89]: array.std().round(decimals=2)
Out[89]: 100.70999999999999

In [90]: np.round(array.std(), decimals=2)
Out[90]: 100.70999999999999

I would like to standard deviation to be round at 2 decimals, but it didn't work so far. How could I fix it? How to make that works with numpy?

David
  • 149
  • 1
  • 3
  • 14
  • 1
    surround it with `int()` – Mangohero1 Sep 25 '17 at 14:06
  • 1
    If you want to stay in `numpy` you can just add `astype()`, e.g. `array.mean().round().astype(np.int)` – AChampion Sep 25 '17 at 14:07
  • 1
    Why do you want to round the std. dev? Is this purely for display / reporting purposes? If so, you want to use string formatting, not numeric rounding. (And if you want to use the _rounded_ value in further computations, you should be asking yourself why you want to needlessly throw away accuracy for those computations.) – Mark Dickinson Sep 25 '17 at 14:52

2 Answers2

1

Python has a builtin function called round(); but to get it how you want, you'll want to cast the std to a float. Something like std_dev = round(float(array.std()), 2) should get you what you want.

Eric Ed Lohmar
  • 1,832
  • 1
  • 17
  • 26
  • 1
    It works, but I would like to make all my computation with numpy. Why it didn't work with numpy? – David Sep 25 '17 at 14:46
  • It looks like this question comes up every now and again on SO. [This comment](https://stackoverflow.com/questions/22261843/python-np-round-with-decimal-option-larger-than-2#comment33813850_22261843), and the subsequent answer, note that the number to which you are trying to round don't have exact binary equivalents. – Eric Ed Lohmar Sep 25 '17 at 14:51
1

Numpy is properly rounding the numbers in the cases you show, but you are seeing the results of floating point precision when the numbers are displayed on screen. If this loss of precision will truly cause a problem for you then you should consider using the decimal package.

import decimal
s = decimal.Decimal(100.70953143681199)
s = round(s, 2)
print(s)
# 100.71
Chris Mueller
  • 6,490
  • 5
  • 29
  • 35