python编程基础——基本数据类型之数字

本文深入探讨Python中数字变量的四则运算细节,解析运算过程中可能出现的精度问题,并介绍了Python标准库math中的常用数学函数及其用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在python中的数字数据类型主要有 整数浮点数两种,在使用时无需定义类型,python会自动帮我们分配好合适的数据类型。

数字

>>> type1<class 'int'>
>>> id(1)
140726521205632

>>> type(1.0)
<class 'float'>
>>> id(1.0)
2088574363376

从上述代码中可以看出python会主动对数字创建一个合适的数据类型的对象。比如前面输入的3就是一个对象。每个对象都会有一个内存地址。不难看出3和3.0虽然在数学中大小是一样的,但在这里,他们是不同的对象。


变量

>>> x=2
>>> x
2
>>> x=6
>>> x
6

python内存引用
引用语义:在python中,变量保存的是对象(值)的引用,我们称为引用语义。采用这种方式,变量所需的存储空间大小一致,因为变量只是保存了一个引用。也被称为对象语义和指针语义。

值语义:有些语言采用的不是这种方式,它们把变量的值直接保存在变量的存储区里,这种方式被我们称为值语义,例如C语言,采用这种存储方式,每一个变量在内存中所占的空间就要根据变量实际的大小而定,无法固定下来。

由于python中的变量都是采用的引用语义,数据结构可以包含基础数据类型,导致了在python中每个变量中都存储了这个变量的地址,而不是值本身;

因此说对象有类型,变量无类型


四则运算

我们先看下面这段代码:

>>> 10/3
3.3333333333333335

>>> 0.1+0.2
0.30000000000000004

>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17

>>> 0.1+0.1+0.1-0.2
0.10000000000000003

看到这些运算,一定会觉得很奇怪,很简单的四则运算为什么就会出错呢?这是因为在计算机计算过程中使用的是二进制运算例如十进制的0.1,转化为二进制是:
0.00011001100110011001100110011001100110011…
无线循环的小数在计算过程中必然会截取有限位数来进行计算。所以会出现上面的现象。

#加法
>>> 2+3
5
#乘法
>>> 2*3
6
#除法
>>> 2/3
0.6666666666666666
#减法
>>> 2-3
-1
#除余
>>> 2%3
2
#返回商和余数
>>> divmod(2,3)
(0, 2)
#保留小数后三位
>>> round(3.141592654, 3)
1.142

>>> round(1.2345,3)
1.234   

Note:The behavior of round()for floats can be surprising:for example,round(2.675,2)gives 2.67 instead of the expected 2.68.This is not a bug:it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.See Floating Point Arithmetic:Issues and Limitations for more information.


函数以及用法

math是python标准库中的,我们可以直接使用:

>>>import math
>>>math.pi
3.141592653589793

通过dir()查看任何模块中所包含的工具:

>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
#通过help查看每个函数的使用方法
>>> help(math.pow)
Help on built-in function pow in module math:

pow(x, y, /)
    Return x**y (x to the power of y).

>>> help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值