0

What is the Python equivalent of these C types:

float
double 
long

I want to represent a float in the above three forms.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
Sam Chance
  • 35
  • 1
  • 1
  • 1

1 Answers1

8

I believe you mean types, not functions. In C, a double is just a double-precision float (meaning smaller numbers are represented more accurately). In Python, it's just a float. Similarly, a long is (was) just an int that stored larger numbers.

In Python 2, there is int, long, and float. However, Python automatically promotes int to long when it grows above sys.intmax. That means there is no point in ever using long in Python. It will turn into a long automatically when it needs to. A float is represented as a double internally.

The short answer is to just use int and float, and don't worry about the underlying implementation. Python abstracts that away for you.

You can convert an int to a float (and back) like this:

#!/usr/bin/python

number = 45
real_number = 3.14159265359

number_as_float = float(number)
real_number_as_int = int(real_number)

See more about the standard Python types here.

Will
  • 24,082
  • 14
  • 97
  • 108
  • 3
    You don't need the "on most platforms": a Python `float` is *always* stored as a C `double` internally (assuming that we're talking about CPython). Of course, what format that C double is depends on the platform, but it's almost always IEEE 754 binary64 on current mainstream platforms. – Mark Dickinson Jan 23 '16 at 09:01
  • 1
    From the Python manual: `Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in sys.float_info.` But I'll remove it from the post and just leave this comment. I feared if I didn't include "on most platforms" someone would point that out ;) – Will Jan 23 '16 at 09:05
  • 1
    We don't, actually. :-) That comment may be outdated. Look at the CPython source, specifically `Include/floatobject.h`, and find the `PyFloatObject` structure. You'll see a `double ob_fval` field for the float value. – Mark Dickinson Jan 23 '16 at 09:08
  • 2
    Actually, that bit of the docs is not outdated; it's simply wrong. :-) If I find enough energy, I'll submit a fix. `sys.float_info` is also based directly on the `DBL_EPSILON`, `DBL_MAX`, etc. macros; there's no facility built into the source for swapping out `double` for another floating-point type (though that would be cool). – Mark Dickinson Jan 23 '16 at 09:12