python 1 2_Python 1.2

本文主要介绍Python中浮点数的相关知识,包括其用于表示非整数,可通过输入带小数点数字或整数除法创建,计算机存储不准确易导致bug。还介绍了浮点数与整数的运算,以及Python支持的求幂、确定商和余数的操作及对应运算符。

Floats#浮点数

Floats are used in Python to represent numbers that aren't integers.

Some examples of numbers that are represented as floats are 0.5 and -7.8237591.

They can be created directly by entering a number with a decimal point, or by using operations such as division on integers. Extra zeros at the number's end are ignored.

Python中使用浮点数来表示非整数的数字。

一些用浮点数表示的数字的例子是0.5和-7.8237591。

它们可以通过输入带有小数点的数字,或者使用整数除法等操作直接创建。数字末尾的额外零将被忽略。

>>> 3/4

0.75

>>> 9.8765000

9.8765

Computers can't store floats perfectly accurately, in the same way that we can't write down the complete decimal expansion of 1/3 (0.3333333333333333...). Keep this in mind, because it often leads to infuriating bugs!

计算机不能完全准确地存储浮点数,就像我们不能写出1/3(0.3333333333333333……)的完整小数展开式一样。请记住这一点,因为它经常会导致溢出bug !

As you saw previously, dividing any two integers produces a float.

A float is also produced by running an operation on two floats, or on a float and an integer.

如前所述,除任何两个整数都会产生一个浮点数。

浮点数也是通过在两个浮点数或浮点数和整数上运行操作生成的。

>>> 8 / 2

4.0

>>> 6 * 7.0

42.0

>>> 4 + 1.65

5.65

A float can be added to an integer, because Python silently converts the integer to a float. However, this implicit conversion is the exception rather the rule in Python - usually you have to convert values manually if you want to operate on them.

浮点数可以添加到整数中,因为Python会悄悄地将整数转换为浮点数。然而,这种隐式转换是Python中的例外,而不是规则——如果您想对值进行操作,通常必须手动转换值。

Exponentiation#求幂

Besides addition, subtraction, multiplication, and division, Python also supports exponentiation, which is the raising of one number to the power of another. This operation is performed using two asterisks.

除了加法、减法、乘法和除法之外,Python还支持求幂,即将一个数的幂提升到另一个数的幂。此操作使用两个星号执行。

>>> 2**5

32

>>> 9 ** (1/2)

3.0

You can chain exponentiations together. In other words, you can rise a number to multiple powers. For example, 2 3 2.

可以把指数链式。换句话说,你可以把一个数提升到几次方。例如,2,3,2。

Quotient & Remainder# 商和余数

To determine the quotient and remainder of a division, use the floor division and modulo operators, respectively.

Floor division is done using two forward slashes.

The modulo operator is carried out with a percent symbol (%).

These operators can be used with both floats and integers.

要确定除法的商和余数,请分别使用底数除法和模运算符。

Floor division使用两个前斜线。

使用百分号(%)执行模运算符。

这些操作符可以同时用于浮点数和整数。

This code shows that 6 goes into 20 three times, and the remainder when 1.25 is divided by 0.5 is 0.25.

这段代码显示20除以6商为3(余数为2),1.25除以0.5余数为0.25(商为2).

>>> 20 // 6

3

>>> 1.25 % 0.5

0.25

In the example above, 20 % 6 will return 2, because 3*6+2 is equal to 20.

在上面的例子中,20% 6将返回2,因为3*6+2 = 20。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值