• 10.6. 数学

    10.6. 数学

    math 模块提供对浮点数学的底层C库函数的访问:

    1. >>> import math
    2. >>> math.cos(math.pi / 4)
    3. 0.70710678118654757
    4. >>> math.log(1024, 2)
    5. 10.0

    random 模块提供了进行随机选择的工具:

    1. >>> import random
    2. >>> random.choice(['apple', 'pear', 'banana'])
    3. 'apple'
    4. >>> random.sample(range(100), 10) # sampling without replacement
    5. [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
    6. >>> random.random() # random float
    7. 0.17970987693706186
    8. >>> random.randrange(6) # random integer chosen from range(6)
    9. 4

    statistics 模块计算数值数据的基本统计属性(均值,中位数,方差等):

    1. >>> import statistics
    2. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
    3. >>> statistics.mean(data)
    4. 1.6071428571428572
    5. >>> statistics.median(data)
    6. 1.25
    7. >>> statistics.variance(data)
    8. 1.3720238095238095

    SciPy项目 <https://scipy.org> 有许多其他模块用于数值计算。