
上QQ阅读APP看书,第一时间看更新
4.3 float类型
浮点类型(float)是表示实数的数据类型,与其他计算机语言的双精度(double)和单精度对应。Python浮点类型的精度与系统相关。
4.3.1 浮点类型字面量
浮点类型字面量可以为带小数点的数字字符串,或用科学记数法表示的数字字符串(前面可以带负号“-”),即浮点型字面量。Python解释器自动创建float型对象实例。
浮点类型字面量的示例如表4-3所示。
表4-3 浮点类型字面量的示例

【例4.5】 浮点类型字面量示例。

4.3.2 float对象
float是Python的内置数据类型,用户可以创建float类型的对象实例,其基本形式如下。

通过创建float对象可以把数值或任何符合格式的字符串转换为float对象。
注意:如果对象x不能转换为float对象,将导致TypeError;如果对象x转换失败,将导致ValueError。特殊字符串'Infinity'、'-Infinity'和'NaN'分别用于表示正无穷大、负无穷大和非数值。
【例4.6】 float对象示例。

4.3.3 float对象的方法
float对象包含的主要方法如表4-4所示。
表4-4 float对象的主要方法

4.3.4 浮点数的运算
浮点数对象支持关系运算、算术运算、位运算符、内置函数、math模块中的数学运算函数以及float对象方法(参见4.3.3节)等运算操作。
在Python语言中,常用的float数据类型对象的运算表达式如表4-5所示。
表4-5 Python常用的浮点数运算表达式

【例4.7】 浮点数运算示例(float_ops.py)。

程序运行结果如图4-2所示。

图4-2 浮点数运算示例程序运行结果
注意:浮点数运算会产生误差。