【问题标题】:What is the Python equivalent of C types float, double and long?C 类型 float、double 和 long 的 Python 等价物是什么?
【发布时间】:2016-01-23 07:02:50
【问题描述】:

这些 C 类型的 Python 等价物是什么:

float
double 
long

我想用以上三种形式表示一个float

【问题讨论】:

  • floatdoublelong 不是函数,它们是类型。而long 是一个 integer 类型。
  • 如果您想要单精度浮点数,您还可以查看NumPyctypes 模块,具体取决于您的需要。

标签: python c floating-point double long-integer


【解决方案1】:

我相信您的意思是类型,而不是函数。在 C 中,double 只是双精度 float(意味着更小的数字表示更准确)。在 Python 中,它只是一个 float。同样,long 是(曾经)只是一个存储更大数字的int

在 Python 2 中,有 intlongfloat。然而,当int 增长到sys.intmax 以上时,Python 会自动将int 提升为long。这意味着在 Python 中使用 long 毫无意义。它会在需要时自动变成longfloat 在内部表示为 double

简短的回答是只使用intfloat,不用担心底层实现。 Python 为您抽象了这些内容。

您可以像这样将int 转换为float(并返回):

#!/usr/bin/python

number = 45
real_number = 3.14159265359

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

详细了解标准 Python 类型 here

【讨论】:

  • 您不需要“在大多数平台上”:Python float总是在内部存储为 C double(假设我们正在谈论CPython)。当然,C double 是什么格式取决于平台,但目前主流平台上几乎都是 IEEE 754 binary64。
  • 来自 Python 手册: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. 但我会将其从帖子中删除并留下此评论。我担心如果我不包括“在大多数平台上”,有人会指出这一点;)
  • 实际上我们没有。 :-) 该评论可能已过时。查看 CPython 源代码,特别是 Include/floatobject.h,并找到 PyFloatObject 结构。您将看到一个 double ob_fval 字段作为浮点值。
  • 实际上,那部分文档并没有过时;这是错误的。 :-) 如果我找到足够的能量,我会提交修复。 sys.float_info也是直接基于DBL_EPSILONDBL_MAX等宏;源代码中没有内置用于将double 替换为另一种浮点类型的工具(尽管那会很酷)。
猜你喜欢
  • 2011-03-15
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 2019-04-02
相关资源
最近更新 更多