0

I am having a problem with the conversion of singles to doubles in Python.

In my program, I receive float values from a C program passed in an array as single precision. When they are converted to a python value, the lower part of numerical conversion is random memory junk. Is there a way to pre-initialize a conversion, such that the minor precision parts are set to zero?

This value mimics the conversion behavior I am seeing:

In [1]: import ctypes

In [2]: in_float = ctypes.c_float(1.2)

In [3]: in_float
Out[3]: c_float(1.2000000476837158)

In [4]: my_val = in_float.value

In [5]: my_val
Out[5]: 1.2000000476837158

I would like it to set the precision values (smaller than the 8th decimal place) to zero, for all converted values. Is there a way to initialize the values so that the missing converted precision is zero? As an example, I am looking for something like this:

In [4]: my_val = zero_double(in_float.value)

In [5]: my_val
Out[5]: 1.2000000000000000

What I'm looking for is some function (call it zero_double() for this example) which will give me a conversion assuming that the missing precision values were 0

RexBarker
  • 1,456
  • 16
  • 14
  • That answer is very close. But in principle, I want the python float (double precision) to initialize all digits to 0. Then when assigning in the c_float (single) precision number, the first 8 digits are written and the rest of the digits remain 0 as they were assigned in the initialization. It seems if the python double was first initialized to 0, then the remaining precision digits should also be 0 – RexBarker Sep 07 '21 at 11:43
  • 1
    How about you use `round`. Something like round(1.2000000476837158, 5) should give you what you want. – Lukas S Sep 07 '21 at 11:45
  • You've already lost the precision if starting with a 32-bit float. Even a 64-bit float has a loss of precision: `format(1.2,'.20')` -> `'1.1999999999999999556'` – Mark Tolonen Sep 07 '21 at 21:03
  • Actually, the first linked answer basically solved the problem: the precision of the original `single` was limited, and python uses a `double` to present it anyway. So it's a display problem. Using `round()` was also a good suggestion. In the end, there is no added precision by doing this, since these minor decimals were made up anyway. The effect is merely cosmetic here. – RexBarker Sep 07 '21 at 21:05
  • Then just format with fewer digits of precision: `format(c_float(1.2).value,'.7')` -> `'1.2'` – Mark Tolonen Sep 07 '21 at 21:39

0 Answers0