Skip to content
Snippets Groups Projects
Commit 2bc45272 authored by Martin Reinecke's avatar Martin Reinecke
Browse files

Issue #179: more sanity checks for arguments to random generators

parent 8f98a8f3
No related branches found
No related tags found
No related merge requests found
Pipeline #
...@@ -32,6 +32,13 @@ class Random(object): ...@@ -32,6 +32,13 @@ class Random(object):
@staticmethod @staticmethod
def normal(dtype, shape, mean=0., std=1.): def normal(dtype, shape, mean=0., std=1.):
if not np.isscalar(mean) or not np.isscalar(std):
raise TypeError("mean and std must be scalars")
if np.issubdtype(type(std), np.complexfloating):
raise TypeError("std must not be complex")
if ((not np.issubdtype(dtype, np.complexfloating)) and
np.issubdtype(type(mean), np.complexfloating)):
raise TypeError("mean must not be complex for a real result field")
if np.issubdtype(dtype, np.complexfloating): if np.issubdtype(dtype, np.complexfloating):
x = np.empty(shape, dtype=dtype) x = np.empty(shape, dtype=dtype)
x.real = np.random.normal(mean.real, std*np.sqrt(0.5), shape) x.real = np.random.normal(mean.real, std*np.sqrt(0.5), shape)
...@@ -42,12 +49,20 @@ class Random(object): ...@@ -42,12 +49,20 @@ class Random(object):
@staticmethod @staticmethod
def uniform(dtype, shape, low=0., high=1.): def uniform(dtype, shape, low=0., high=1.):
if not np.isscalar(low) or not np.isscalar(high):
raise TypeError("low and high must be scalars")
if (np.issubdtype(type(low), np.complexfloating) or
np.issubdtype(type(high), np.complexfloating)):
raise TypeError("low and high must not be complex")
if np.issubdtype(dtype, np.complexfloating): if np.issubdtype(dtype, np.complexfloating):
x = np.empty(shape, dtype=dtype) x = np.empty(shape, dtype=dtype)
x.real = np.random.uniform(low, high, shape) x.real = np.random.uniform(low, high, shape)
x.imag = np.random.uniform(low, high, shape) x.imag = np.random.uniform(low, high, shape)
elif np.issubdtype(dtype, np.integer): elif np.issubdtype(dtype, np.integer):
x = np.random.random.randint(low, high+1, shape) if not (np.issubdtype(type(low), np.integer) and
np.issubdtype(type(high), np.integer)):
raise TypeError("low and high must be integer")
x = np.random.randint(low, high+1, shape)
else: else:
x = np.random.uniform(low, high, shape) x = np.random.uniform(low, high, shape)
return x.astype(dtype, copy=False) return x.astype(dtype, copy=False)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment