8000 ENH/BUG: Allow multinomial to check pvals with other float types by bashtage · Pull Request #16732 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

ENH/BUG: Allow multinomial to check pvals with other float types #16732

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion numpy/random/_generator.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3737,7 +3737,18 @@ cdef class Generator:
pix = <double*>np.PyArray_DATA(parr)
check_array_constraint(parr, 'pvals', CONS_BOUNDED_0_1)
if kahan_sum(pix, d-1) > (1.0 + 1e-12):
raise ValueError("sum(pvals[:-1]) > 1.0")
msg = "sum(pvals[:-1]) > 1.0"
# When floating, but not float dtype, and close, improve the error
# 1.0001 works for float16 and float32
if (isinstance(pvals, np.ndarray) and
pvals.dtype != float and
np.issubdtype(pvals.dtype, np.floating) and
pvals.sum() < 1.0001):
msg += (". pvals has been cast to double before checking "
"the sum. Changes in precision when casting may "
"produce violations even if pvals.sum() <= 1 when "
"evaluated in its original dtype.")
raise ValueError(msg)

if np.PyArray_NDIM(on) != 0: # vector
check_array_constraint(on, 'n', CONS_NON_NEGATIVE)
Expand Down
8 changes: 8 additions & 0 deletions numpy/random/tests/test_generator_mt19937.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,14 @@ def test_multidimensional_pvals(self):
assert_raises(ValueError, random.multinomial, 10, [[[0], [1]], [[1], [0]]])
assert_raises(ValueError, random.multinomial, 10, np.array([[0, 1], [1, 0]]))

def test_multinomial_pvals_float32(self):
x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
pvals = x / x.sum()
random = Generator(MT19937(1432985819))
match = r"[\w\s]*pvals has been cast to double"
with pytest.raises(ValueError, match=match):
random.multinomial(1, pvals)

class TestMultivariateHypergeometric:

Expand Down
0