0

I need to precisely save a lot of floating numbers to a file in C++ program, and then read them in Python.

You known that the precision of floating numbers may be lost when we convert them into/out from string.

I'm wondering that "Is there an equivalent of union in Python?" If so, I can do it as following:

C++ program:

union Convert_t {
    // this occupys 8 bytes
    double      asDouble;

    // this occupies 8 bytes too, so we just only treat a double as a int64
    int64_t     asIntegr;
};

// when preparing data
Convert_t data;
data.asDouble = real_data;
out_csv_stream << data.asIntegr << ',';

When read data in Python program:

import typing
import pandas as pd

# now the type of contents should be int64
pd.read_csv(csv_path)
# I don't known how to writing correctly follow lines
class PyConvert : typing.Union 
    asDouble : numpy.float64
    asIntegr : numpy.int64

I think my question is different to that question and answer. That answer doesn't show how to convert data into a floating type, and it was using cdll.LoadLibrary() that was not required for me.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Leon
  • 1,489
  • 1
  • 12
  • 31
  • Thank @wohlstad! But I haven't found how to get floating number in that post, sorry! – Leon Sep 02 '23 at 16:03
  • The accepted answer in the duplicate uses [ctypes](https://docs.python.org/3.6/library/ctypes.html#ctypes.c_uint), which supports floating point types. Anyway if the duplicate post does not answer your question you can apply to reopen it (maybe edit it and explain why that post does not help you). – wohlstad Sep 02 '23 at 16:06
  • You appear to be using iostreams. That makes your "C program" in fact C++. And it matters. In particular, the C++ rules around union usage differ from the C rules for the same: your C++ code has undefined behavior on account of reading a different member of the union than was last written, but similar C code could have defined behavior. – John Bollinger Sep 02 '23 at 16:35
  • 2
    I think the union is a red herring anyway. Even in C, I would not use a union for your purpose. If I wanted to write the internal representation of a `double` to a file then I would do it directly, with `fwrite()`. Even more so if I wanted to write an array of `double`s. – John Bollinger Sep 02 '23 at 16:37
  • "You known that the precision of floating numbers may be lost when we convert them into/out from string." The standard mandates an interchange format that preserves all precision. – qwr Sep 02 '23 at 19:02

0 Answers0