5

I have not encountered any problems thus far, so this is a question purely out of curiosity.

In Python I usually define floats and arrays of floats like this:

import numpy as np

s = 1.0
v = np.array([1.0, 2.0, 3.0])

In the case above s is a float, but the elements of v are of type numpy.float64.

To be more consistent I could, for example, do this instead:

import numpy as np

s = np.float64(1.0)
v = np.array([1.0, 2.0, 3.0])

Are there cases, from an accuracy/precision point of view, where it is recommended to use the "consistent" approach? What kind of errors, if any, can I expect in the "inconsistent" approach?

Numaerius
  • 383
  • 3
  • 10

1 Answers1

3

Python (at least CPython) uses doubles for it's float type internally - and doubles are 64bit floats (maybe not always but I haven't found a platform + compiler where doubles weren't 64bit floats).

So you shouldn't expect any kind of problems no matter if you keep them as float or np.float64.

However if you use Pythons float and NumPys np.float32 you could expect differences as the float has more precision (64 bits) than a np.float32 (32 bits).

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 1
    The assumption that C doubles have 8 bytes is still hard-wired into various places in the CPython source, so if CPython were ever to meet a platform where the double wasn't 64 bits, it would probably break quite badly. (And yes, I'm assuming that bytes have 8 bits, but if CPython ever met a platform where bytes didn't have 8 bits, it would break even badlier.) So IOW, your assumption that doubles are 64-bit floats is a fairly safe one. :-) – Mark Dickinson Aug 08 '17 at 14:46
  • Here's an example of one such place where 8-byte doubles are assumed, in the marshal module: https://github.com/python/cpython/blob/v3.6.2/Python/marshal.c#L362-L369 – Mark Dickinson Aug 08 '17 at 14:49
  • @MarkDickinson That's good to know. I only did a superficial search and I assumed there *might* be differences when I found a question where the author wanted to ["Ensure C++ doubles are 64 bits"](https://stackoverflow.com/questions/752309/ensuring-c-doubles-are-64-bits). – MSeifert Aug 08 '17 at 14:59