basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    Chapter 3PythonBasics

    Numbers in Python: integers without a limit, fractions with an error

    Python has two kinds of numbers. Integers (int) have any length and are exact. Fractions (float) carry an error, which is why 0.1 + 0.2 is 0.30000000000000004. Convert a server’s uptime from seconds into days and hours, go through division, remainder and rounding, and find out where 69 GB of a 1 TB disk went.

    New hereArithmetic: //, %, roundimport

    What you’ll get

    On Linux a server’s uptime lives in /proc/uptime, in seconds. Convert it into days, hours and minutes:

    # uptime.py
    uptime = 1_234_567   # seconds
    days = uptime // 86400
    hours = uptime % 86400 // 3600
    minutes = uptime % 3600 // 60
    print(days, "d", hours, "h", minutes, "min")
    python uptime.py
    # 14 d 6 h 56 min

    // is division without a remainder, % the remainder. There are 86,400 seconds in a day: 14 whole days, and the same trick pulls hours and minutes out of the remainder. The underscores in 1_234_567 are for the eye; Python skips them.

    What will it print?
    print(round(2.5), round(3.5))
    What will it print?
    Answer:
    2 4

    Python rounds halves to even: 2.5 goes to 2, 3.5 to 4. That way, when many rounded numbers are summed, the errors cancel out instead of piling up in one direction.

    How it works: integers are exact, fractions aren’t

    An int takes as much memory as it needs, so its length is unlimited and arithmetic is exact:

    >>> 2 ** 100
    1267650600228229401496703205376

    A float is 64 bits in binary: about 16 significant digits and a limit of about 1.8e308. Most decimal fractions are infinite in binary, like ⅓ in decimal, so the nearest value is stored:

    >>> 0.1 + 0.2
    0.30000000000000004
    >>> 0.1 + 0.2 == 0.3
    False
    >>> 10 / 3
    3.3333333333333335

    For measurements — sizes, times, speeds — an error in the 16th digit doesn’t show. It shows in two places: comparing with ==, and money, where cents add up by the thousand. Compare with math.isclose, and count money with the decimal module or in whole cents:

    import math
    from decimal import Decimal
    
    print(math.isclose(0.1 + 0.2, 0.3))       # True
    print(Decimal("0.1") + Decimal("0.2"))    # 0.3

    import math loads the math module — it’s in the standard library, nothing to install (Running Python). After that, write its functions with a dot: math.isclose, math.ceil. from decimal import Decimal takes a single name from a module, and you write it without a prefix. Put the import lines at the top of the file.

    Division, remainder and powers

    Code Result What it does
    7 / 2 3.5 division; the answer is always a float, even 6 / 2 is 3.0
    7 // 2 3 division without a remainder, rounding down: -7 // 2 is -4
    7 % 2 1 the remainder: an even number has n % 2 == 0
    2 ** 10 1024 a power; 2 ** 0.5 is a square root, 1.4142135623730951
    abs(-5) 5 absolute value
    max(3, 7, 1), min(…) 7, 1 the largest and the smallest
    round(2.675, 2) 2.67 to two places; 2.675 is stored slightly lower, so it isn’t 2.68
    math.ceil(4.1) 5 up to an integer: how many disks you need for 4.1 TB
    math.floor(4.9) 4 down to an integer

    An integer with a fraction gives a fraction: 3 * 0.5 is 1.5. An integer from a string is int("100"), from a fraction int(4.7), with the tail dropped: that’s covered in Variables and types.

    Where 69 GB went: decimal and binary prefixes

    Windows shows a 1 TB disk as 931 GB. The manufacturer counts a kilobyte as 1000 bytes; Windows counts 1024:

    >>> 1_000_000_000_000 / 1000 ** 3
    1000.0
    >>> 1_000_000_000_000 / 1024 ** 3
    931.3225746154785

    The bytes are the same; the units differ. In the standard the binary ones are KiB, MiB, GiB; Windows writes “GB” and means GiB. ISPs, like disk makers, count in decimal — which is why Variables and types divided by 1000.

    Hexadecimal, octal, binary

    In configs numbers aren’t always decimal: the color #ff8800, a MAC address, chmod 755 permissions. Python writes them with a prefix and converts both ways:

    Code Result Where you see it
    0xff, int("ff", 16) 255 colors, MACs, bytes in a dump
    0o755, int("755", 8) 493 file permissions on Linux
    0b1010 10 bits, masks
    hex(255), oct(493), bin(10) '0xff', '0o755', '0b1010' back into a string

    int("0x1f") without a base is a ValueError: read a string with a prefix using the base, int("0x1f", 16), or without the prefix.

    Take it further

    How many 4 TB disks you need for 10.5 TB of data

    Divide the volume by the disk size and round up — math.ceil. Load the module on the first line: import math.

    import math
    
    print(math.ceil(10.5 / 4))
    # 3
    Permissions 644 — to a number and back to octal

    int with base 8 reads a string of digits; oct returns the form with the 0o prefix.

    mode = int("644", 8)
    print(mode, oct(mode))
    # 420 0o644
    Is a number even, and is the year divisible by 4

    An even number’s remainder when divided by 2 is 0. The == comparison gives True or False, which you can print right away.

    print(10 % 2 == 0)      # True
    print(2026 % 4 == 0)    # False

    If it doesn’t work

    0.1 + 0.2 == 0.3 gives False

    Cause
    A fraction is stored in binary, and 0.1 can’t be written exactly in it: the sum comes out as 0.30000000000000004.
    Fix
    Don’t compare fractions with ==: use math.isclose(0.1 + 0.2, 0.3) or round(…, 2) == 0.3. For money, decimal.Decimal("0.1") or counting in whole cents.

    round(2.5) gives 2, and round(3.5) gives 4

    Cause
    Python rounds halves to even — that way less error accumulates when many numbers are rounded in a row.
    Fix
    If you need “half up” for positive numbers, use math.floor(x + 0.5). For display you don’t need rounding at all: f"{x:.1f}".

    ZeroDivisionError: division by zero

    Cause
    Dividing by zero: /, // and % alike. Usually the zero came from the data — an empty file, a zero counter.
    Fix
    Check the divisor before dividing — conditions are in the Conditions chapter.

    OverflowError: (34, 'Result too large')

    Cause
    A fraction went past the float limit of about 1.8e308: 10.0 ** 400. Integers have no limit; fractions do.
    Fix
    Compute in integers if you can: 10 ** 400 works. For a huge fraction, the decimal module.

    ValueError: Exceeds the limit (4300 digits) for integer string conversion

    Cause
    An integer longer than 4300 digits is being converted to a string — print, str(), an f-string. The limit protects against slow conversion of giant numbers.
    Fix
    Raise the limit: import sys, then sys.set_int_max_str_digits(0) — no limit.