6

I want to preallocate memory for the output of an array operation, and I need to know what dtype to make it. Below I have a function that does what I want it to do, but is terribly ugly.

import numpy as np

def array_operation(arr1, arr2):
    out_shape = arr1.shape
    # Get the dtype of the output, these lines are the ones I want to replace.
    index1 = ([0],) * arr1.ndim
    index2 = ([0],) * arr2.ndim
    tmp_arr = arr1[index1] * arr2[index2]
    out_dtype = tmp_arr.dtype
    # All so I can do the following.
    out_arr = np.empty(out_shape, out_dtype)

The above is pretty ugly. Does numpy have a function that does this?

5
  • Are you interested in the dtype after multiplication only? Commented Sep 2, 2011 at 15:35
  • @unutbu, Can you explain why you ask? Commented Sep 2, 2011 at 15:47
  • @Mike Graham: On could enumerate all the basic dtypes, compute the resultant types of all pairs after multiplication, and store result in a dictionary. This wouldn't work for more complicated dtypes though... Commented Sep 2, 2011 at 15:55
  • @ubutbu, Can you provide an example of a time another operation gives a different resulting original-dtypes-dependent dtype for multiplication and another operation? Commented Sep 2, 2011 at 16:55
  • @Mike Graham: I was thinking more about arbitrary (numpy) function calls. Commented Sep 2, 2011 at 17:15

2 Answers 2

8

You are looking for numpy.result_type.

(As an aside, do you realize that you can access all multi-dimensional arrays as 1d arrays? You don't need to access x[0, 0, 0, 0, 0] -- you can access x.flat[0].)

Sign up to request clarification or add additional context in comments.

2 Comments

What numpy version are you using? 1.3.0 doesn't seem to have a result_type function.
To your aside: x[0] would 'full slice' all other axes except the first. That could be a lot of extra multiplication.
1

For those using numpy version < 1.6, you could use:

def result_type(arr1, arr2):
    x1 = arr1.flat[0]
    x2 = arr2.flat[0]
    return (x1 * x2).dtype

def array_operation(arr1, arr2):
    return np.empty(arr1.shape, result_type(arr1, arr2))

This isn't very different from the code you posted, though I think arr1.flat[0] is a slight improvement over index1 = ([0],) * arr1.ndim; arr1[index1].

For numpy version >= 1.6, use Mike Graham's answer, np.result_type

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.