Skip to content

Commit 57d4148

Browse files
authored
FIX: markov: Respect dtype of P in cdfs (#592)
1 parent 267a9bb commit 57d4148

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

quantecon/markov/core.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,6 @@ def get_index(self, value):
273273
else:
274274
raise ValueError('invalid value')
275275

276-
277276
def _get_index(self, value):
278277
"""
279278
Return the index of the given value in `state_values`.
@@ -420,7 +419,7 @@ def stationary_distributions(self):
420419
def cdfs(self):
421420
if (self._cdfs is None) and not self.is_sparse:
422421
# See issue #137#issuecomment-96128186
423-
cdfs = np.empty((self.n, self.n), order='C')
422+
cdfs = np.empty((self.n, self.n), order='C', dtype=self.P.dtype)
424423
np.cumsum(self.P, axis=-1, out=cdfs)
425424
self._cdfs = cdfs
426425
return self._cdfs
@@ -431,7 +430,7 @@ def cdfs1d(self):
431430
data = self.P.data
432431
indptr = self.P.indptr
433432

434-
cdfs1d = np.empty(self.P.nnz, order='C')
433+
cdfs1d = np.empty(self.P.nnz, order='C', dtype=data.dtype)
435434
for i in range(self.n):
436435
cdfs1d[indptr[i]:indptr[i+1]] = \
437436
data[indptr[i]:indptr[i+1]].cumsum()

quantecon/markov/tests/test_core.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
import numpy as np
1111
from scipy import sparse
1212
import itertools
13-
from numpy.testing import assert_allclose, assert_array_equal, assert_raises
13+
from numpy.testing import (
14+
assert_allclose, assert_array_equal, assert_array_less, assert_raises
15+
)
1416
from nose.tools import eq_, ok_, raises
1517

1618
from quantecon.markov import (
@@ -339,6 +341,33 @@ def test_simulate_for_matrices_with_C_F_orders():
339341
assert_array_equal(computed_F, sample_path)
340342

341343

344+
def test_simulate_issue591():
345+
"""
346+
Test MarkovChasin.simulate for P with dtype=np.float32
347+
https://github.com/QuantEcon/QuantEcon.py/issues/591
348+
"""
349+
num_states = 5
350+
transition_states = 4
351+
352+
transition_seed = 2
353+
random_state = np.random.RandomState(transition_seed)
354+
transitions = random_state.uniform(0., 1., transition_states)
355+
transitions /= np.sum(transitions)
356+
P = np.zeros((num_states, num_states), dtype=np.float32)
357+
P[0, :transition_states] = transitions
358+
P[1:, 0] = 1.
359+
mc = MarkovChain(P=P)
360+
361+
simulate_seed = 22220
362+
ts_length = 10000
363+
seq = mc.simulate(
364+
ts_length=ts_length, init=0, num_reps=1, random_state=simulate_seed
365+
)
366+
max_state_in_seq = np.max(seq)
367+
368+
assert_array_less(max_state_in_seq, num_states)
369+
370+
342371
def test_mc_sample_path():
343372
P = [[0.4, 0.6], [0.2, 0.8]]
344373
Ps = [P, sparse.csr_matrix(P)]

0 commit comments

Comments
 (0)