Is there a way to specify default dtype that\'s used with constructs like np.array(1.)?
In particular I want np.array(1.) to be np.fl
You could use np.float32 or np.int32 as np.ndarray constructor:
>>> np.float32([1.])
array([ 1.], dtype=float32)
>>> np.int32([1])
array([1], dtype=int32)
but that returns a numpy-scalar if given a scalar input (not a rank 0 array):
>>> np.float32(1)
1.
>>> np.asarray(np.float32(1)) # Use np.asarray to convert it to an array
array(1.0, dtype=float32)
Redefining the default dtype seems to be not so easy, see also:
If you don't care additional overhead you can always use a dictionary as "switch" to get correct dtype for those you find inappropriate:
defaults = {np.dtype('int64'): np.int32,
np.dtype('float64'): np.float32}
before = 1.
np.array(before, dtype=defaults.get(np.result_type(before), None))
This will however fail with complicated types like characters (strings) or objects.