Skip to content

Commit

Permalink
Fix over/underflow with numpy.int16 (#36)
Browse files Browse the repository at this point in the history
* Fix under/overflow with numpy int16
* v3.7.2
  • Loading branch information
tammoippen authored Sep 11, 2020
1 parent 2fc3d58 commit e7b43e4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
14 changes: 13 additions & 1 deletion plotille/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ def roundeven(x):
return x_r


def _numpy_to_native(x):
# cf. https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html
if ('<class \'numpy.' in str(type(x)) or '<type \'numpy.' in str(type(x))) and callable(getattr(x, 'item')):
return x.item()
return x


def hist(X, bins):
"""Create histogram similar to `numpy.hist()`
Expand All @@ -69,6 +76,10 @@ def hist(X, bins):
if xmin == xmax:
xmin -= 0.5
xmax += 0.5

xmin = _numpy_to_native(xmin)
xmax = _numpy_to_native(xmax)

delta = xmax - xmin
is_datetime = False
if isinstance(delta, timedelta):
Expand All @@ -79,7 +90,8 @@ def hist(X, bins):

y = [0] * bins
for x in X:
delta = (x - xmin)
x_ = _numpy_to_native(x)
delta = (x_ - xmin)
if isinstance(delta, timedelta):
delta = timestamp(delta)
x_idx = min(bins - 1, int(delta // xwidth))
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[tool.poetry]

name = "plotille"
version = "3.7.1"
version = "3.7.2"
description = "Plot in the terminal using braille dots."
authors = ["Tammo Ippen <tammo.ippen@posteo.de>"]
license = "MIT"
Expand Down
16 changes: 16 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np

from plotille._util import hist


def test_hist_neg_idx():
x = np.random.randint(-32767, 32767, 100, dtype=np.int16)

expect = np.histogram(x, bins=8)
actual = hist(x, bins=8)

assert list(expect[0]) == actual[0] # counts
assert list(expect[1]) == actual[1] # bins

0 comments on commit e7b43e4

Please sign in to comment.