0

I have a PyFloatObject that I want to convert to a C float. However, PyObjectFloat only provides a conversion to double. Can I safely cast a double to a float, or is there a function to convert PyObject to float i.e. PyObject_AsFloat.

3 Answers 3

2

From the docs:

Floating point numbers are usually implemented using double in C;

In other words, the Python float type is just a C double, so there is not magic Python function to convert a Python float to a C float other than what is normally available with C to convert double to float.

0

Short answer is yes, as long as your 'double' will fit (with respect to magnitude) into a 'float'. however you may need to round it or truncate it to single precision.

using IEEE 754 floating point representations....

"float is defined as IEEE 754 single precision, double is defined as double precision, and long double is defined as IEEE 754 extended precision or some form of quad precision where available (e.g., Intel 80 bit double extended precision on x86 or x86-64 platforms), else double precision. Previously, all C90 floating operations were defined to occur in double-precision, with subsequent rounding to single precision, to store results, where necessary."

Data quoted regarding '754 is from http://en.wikipedia.org/wiki/C99 (c99 c spec description on wikipedia) while it isn't python specific, IEEE 754 is general, and not c-specific)

What version of python are you using? You may want to use (from https://docs.python.org/2/c-api/float.html)

double PyFloat_AsDouble(PyObject *pyfloat) Return a C double representation of the contents of pyfloat. If pyfloat is not a Python floating point object but has a float() method, this method will first be called to convert pyfloat into a float. This method returns -1.0 upon failure, so one should call PyErr_Occurred() to check for errors.

3
  • my understanding is that the difference in size of both the exponent and mantissa would make manual coercion of a double to a float somewhat non-trivial and potentially dangerous Jan 14, 2015 at 20:13
  • yes, the exponent is the 'fit' part. Doubles and Floats are both approximations, there will be loss of precision in almost all conversion cases anyway.
    – david1024
    Jan 14, 2015 at 20:16
  • loss of precision is inevitable, but bit level manipulation of doubles to approximate a float sounds like there would be inevitable edge cases in which serious errors occur due to the primitive nature of the conversion method. Jan 14, 2015 at 20:17
0

sprintf into a buffer followed by atoi seems to do the trick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.