Python Lesson III

Author: sandyzikun

大致是一些有关变量类型的笔记.

  1. 一般情况下, 整数之间加减法, 乘法, 乘方, 整除运算返回整数

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    >>> 3 + 9
    12

    >>> 3 - 9
    -6

    >>> 3 * 9
    27

    >>> 2 ** 3939
    5716798967508453493714192804305490605496026077526169067187526404157774662585244740704047054074121902096017303618635817529673213323940491673776027903866672075290937210344109352184731773030901412680539610806679203355518205805208608618313632784205695757745040946702154910218710413906710234911378989664574640787972977139860640060706935710932920447668820444760900580808259711324568138846382165643481227736988189256152244948885390878064629174385532731900942331161496913988217853963252284120978940332456836838447647542799288317724820692662525122542208804308016464573217427171168059511289459224765488214021372940134206411267302745696677627589737226580177932139798311640319697182992650188685192583687722619865762920218361356162969978008571375356011772264881692753209752030641409554483327454328349912285302997077932993078309280930586159583441747134290086841663924166268842405630614696130920121262777744784246397278688753788898523944746071963553820864212717560115203938846399348144358229218041398530115847850290997279286827878003518330533401624751563120057679904326985382321201837124067889869166774237277768464845019027057393248518241620639392996725996422924666789747361779242589346148957592485888

    >>> 39 // 4
    9
  2. float运算返回float, 整数间非整除运算返回float

    Python
    1
    2
    3
    4
    5
    >>> 9 / 3
    3.0

    >>> 3.9 + 0.1
    4.0
  3. 三种取整方法效果比较(其中的正号+是为了强调输出为正数, 而非解释器真的在输出时会带有正号)

    Python
    1
    2
    3
    4
    5
    6
    7
    >>> import math, numpy as np

    >>> round(3.5)
    4

    >>> round(-3.5)
    -4
Methods \ Values -3.9 -3.2 +3.2 +3.9
int() / np.int()1 -3 -3 +3 +3
round() -4 -3 +3 +4
math.floor() -4 -4 +3 +3
math.ceil() -3 -3 +4 +4
np.floor() -4.0 -4.0 +3.0 +3.0
np.round() -4.0 -3.0 +3.0 +4.0
np.ceil() -3.0 -3.0 +4.0 +4.0

由此我们可以看出,

  1. built-inint()实质为整数部分, 所以
    • int(正数)表现为向下取整,
    • int(负数)表现为向上取整;
  2. 标准库math.floor(), .ceil()built-inround()
    为数轴上的向下或上以及舍入取整;
  3. NumPy.floor(), .round(), .ceil()统一返回NumPy的默认类型,
    NumPy初始设置的默认类型为float32,
    但是运算得到的浮点可以通过.astype(int)进行向整型的转换, 这一点会在日后有关NumPy的部分细讲;
  4. 舍入时统一四舍五入, 不论正负;
1. np.int等变量类型转换方法已被弃用, 取而代之的是使用built-in的类名或函数名, 这些传入NumPyndarray对象时会自动转换为NumPy中的对应类型, 参见 NumPy 1.20.0 Release Notes - Deprecations