29

Is there any clean way of setting numpy to use float32 values instead of float64 globally?

3
  • 2
    Closely related: stackoverflow.com/questions/5350342/… Commented Apr 19, 2011 at 20:33
  • 3
    Also an interesting discussion on scipy list: old.nabble.com/switching-to-float32-ts24203533.html#a24203533 Commented Apr 19, 2011 at 20:41
  • Saw the nabble conversation but missed the float128 (thanks sven), and it appears they're both saying the same thing, 'No, not really'. On the Nabble discussion there was then mention of adding it to the cookbook which would be nice. I myself just did a few hacks similar to the float128 question sven mentioned (and answered). Pity Commented Apr 20, 2011 at 0:03

3 Answers 3

13

Not that I am aware of. You either need to specify the dtype explicitly when you call the constructor for any array, or cast an array to float32 (use the ndarray.astype method) before passing it to your GPU code (I take it this is what the question pertains to?). If it is the GPU case you are really worried about, I favor the latter - it can become very annoying to try and keep everything in single precision without an extremely thorough understanding of the numpy broadcasting rules and very carefully designed code.

Another alternative might be to create your own methods which overload the standard numpy constructors (so numpy.zeros, numpy.ones, numpy.empty). That should go pretty close to keeping everything in float32.

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

2 Comments

That's what I'm doing for the GPU case, but I was concerned about direct comparison between CPU bound equivalent calculation precision for testing, as part of a 'weird-bug-hunt'
Is this comment still valid concerning the broadcasting rules? If arrays are declared with dtype float32, is there then any risk in implicit conversions or broadcasting?
7

This question showed up on the NumPy issue tracker. The answer is:

There isn't, sorry. And I'm afraid we're unlikely to add such a thing[.]

Comments

3

For each function you can overload by:

def array(*args, **kwargs):
    kwargs.setdefault("dtype", np.float32)
    return np.array(*args, **kwargs)

As posted by njsmith on github

1 Comment

dtype can be a positional argument as well, so this can break sometimes

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.