[从头学python] 第03节 让我们来学习math

本节目标:
(1) 学习标准库math, cmath, numbers, decimal, fractions, random模块
(2) 学习标准库array模块



实现步骤:

(1) math库

>>> import math
>>> help(math)
Help on built-in module math:

NAME
    math

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.
	
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 
'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 
'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 
'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 
'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

(2) cmath库

>>> import cmath
>>> help(cmath)
Help on built-in module cmath:

NAME
    cmath

DESCRIPTION
    This module is always available. It provides access to mathematical
    functions for complex numbers.
	
>>> dir(cmath)
['__doc__', '__loader__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 
'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 
'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

(3) numbers库

>>> import numbers
>>> help(numbers)
Help on module numbers:

NAME
    numbers - Abstract Base Classes (ABCs) for numbers, according to PEP 3141.

DESCRIPTION
    TODO: Fill out more detailed documentation on the operators.

CLASSES
    builtins.object
        Number
            Complex
                Real
                    Rational
                        Integral
    
    class Complex(Number)
     |  Complex defines the operations that work on the builtin complex type.
     |  
     |  In short, those are: a conversion to complex, .real, .imag, +, -,
     |  *, /, abs(), .conjugate, ==, and !=.
     |  
     |  If it is given heterogenous arguments, and doesn't have special
     |  knowledge about them, it should fall back to the builtin complex
     |  type as described below.
     |  
     |  Method resolution order:
     |      Complex
     |      Number
     |      builtins.object

>>> dir(numbers)
['ABCMeta', 'Complex', 'Integral', 'Number', 'Rational', 'Real', '__all__', '__builtins__', 
'__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', 
'__package__', 'abstractmethod']

(4) decimal库

>>> help(decimal)
Help on module decimal:

NAME
    decimal

DESCRIPTION
    This is an implementation of decimal floating point arithmetic based on
    the General Decimal Arithmetic Specification:
    
        http://speleotrove.com/decimal/decarith.html
    
    and IEEE standard 854-1987:
    
        http://en.wikipedia.org/wiki/IEEE_854-1987
    
    Decimal floating point has finite precision with arbitrarily large bounds.

>>> dir(decimal)
['BasicContext', 'Clamped', 'Context', 'ConversionSyntax', 'Decimal', 'DecimalException', 
'DecimalTuple', 'DefaultContext', 'DivisionByZero', 'DivisionImpossible', 
'DivisionUndefined', 'ExtendedContext', 'FloatOperation', 'HAVE_THREADS', 'Inexact', 
'InvalidContext', 'InvalidOperation', 'MAX_EMAX', 'MAX_PREC', 'MIN_EMIN', 'MIN_ETINY', 
'Overflow', 'ROUND_05UP', 'ROUND_CEILING', 'ROUND_DOWN', 'ROUND_FLOOR', 'ROUND_HALF_DOWN', 
'ROUND_HALF_EVEN', 'ROUND_HALF_UP', 'ROUND_UP', 'Rounded', 'Subnormal', 'Underflow', 
'__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', 
'__version__', 'getcontext', 'localcontext', 'setcontext']

>>> help(decimal.Context)
Help on class Context in module decimal:

class Context(builtins.object)
 |  The context affects almost all operations and controls rounding,
 |  Over/Underflow, raising of exceptions and much more. A new context
 |  can be constructed as follows:
 |  
 |      >>> c = Context(prec=28, Emin=-425000000, Emax=425000000,
 |      ...             rounding=ROUND_HALF_EVEN, capitals=1, clamp=1,
 |      ...             traps=[InvalidOperation, DivisionByZero, Overflow],
 |      ...             flags=[])
 |      >>>

 >>> dir(decimal.Context)
['Emax', 'Emin', 'Etiny', 'Etop', '__class__', '__copy__', '__delattr__', '__dir__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'_apply', '_unsafe_setemax', '_unsafe_setemin', '_unsafe_setprec', 'abs', 'add', 'canonical'
, 'capitals', 'clamp', 'clear_flags', 'clear_traps', 'compare', 'compare_signal', 
'compare_total', 'compare_total_mag', 'copy', 'copy_abs', 'copy_decimal', 'copy_negate', 
'copy_sign', 'create_decimal', 'create_decimal_from_float', 'divide', 'divide_int', 'divmod'
, 'exp', 'fma', 'is_canonical', 'is_finite', 'is_infinite', 'is_nan', 'is_normal', 'is_qnan'
, 'is_signed', 'is_snan', 'is_subnormal', 'is_zero', 'ln', 'log10', 'logb', 'logical_and', 
'logical_invert', 'logical_or', 'logical_xor', 'max', 'max_mag', 'min', 'min_mag', 'minus', 
'multiply', 'next_minus', 'next_plus', 'next_toward', 'normalize', 'number_class', 'plus', 
'power', 'prec', 'quantize', 'radix', 'remainder', 'remainder_near', 'rotate', 'rounding', 
'same_quantum', 'scaleb', 'shift', 'sqrt', 'subtract', 'to_eng_string', 'to_integral', 
'to_integral_exact', 'to_integral_value', 'to_sci_string']

>>> decimal.getcontext().prec=6
>>> decimal.Decimal(1)/decimal.Decimal(6)
Decimal('0.166667')

>>> help(decimal.Context.to_integral_exact)
Help on method_descriptor:

to_integral_exact(...)
    to_integral_exact(x) - Round to an integer. Signal if the result is
    rounded or inexact.
	
>>> help(decimal.Context.to_sci_string)
Help on method_descriptor:

to_sci_string(...)
    to_sci_string(x) - Convert a number to a string using scientific notation.

>>> decimal.getcontext().to_sci_string(decimal.Decimal(6000.666))
'6000.6660000000001673470251262187957763671875'
>>> decimal.Decimal(6000.666)
Decimal('6000.6660000000001673470251262187957763671875')
>>> decimal.getcontext().to_integral_exact(decimal.Decimal(6000.666))
Decimal('6001')

(5) fractions库

>>> help(fractions)
Help on module fractions:

NAME
    fractions - Fraction, infinite-precision, real numbers.

CLASSES
    numbers.Rational(numbers.Real)
        Fraction
    
    class Fraction(numbers.Rational)
     |  This class implements rational numbers.
     |  
     |  In the two-argument form of the constructor, Fraction(8, 6) will
     |  produce a rational number equivalent to 4/3. Both arguments must
     |  be Rational. The numerator defaults to 0 and the denominator
     |  defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
     |  
     |  Fractions can also be constructed from:
     |  
     |    - numeric strings similar to those accepted by the
     |      float constructor (for example, '-2.3' or '1e10')
     |  
     |    - strings of the form '123/456'
     |  
     |    - float and Decimal instances
     |  
     |    - other Rational instances (including integers)
     |  
     |  Method resolution order:
     |      Fraction
     |      numbers.Rational
     |      numbers.Real
     |      numbers.Complex
     |      numbers.Number
     |      builtins.object

>>> dir(fractions)
['Decimal', 'Fraction', '_PyHASH_INF', '_PyHASH_MODULUS', '_RATIONAL_FORMAT', '__all__', 
'__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', 
'__name__', '__package__', 'gcd', 'math', 'numbers', 'operator', 're', 'sys']

>>> fractions.Decimal(1.25)
Decimal('1.25')
>>> fractions.Fraction(1.25)
Fraction(5, 4)
>>> fractions.gcd(100, 25)
25

>>> help(fractions.operator)
Help on built-in module operator:

NAME
    operator - Operator interface.

DESCRIPTION
    This module exports a set of functions implemented in C corresponding
    to the intrinsic operators of Python.  For example, operator.add(x, y)
    is equivalent to the expression x+y.  The function names are those
    used for special methods; variants without leading and trailing
    '__' are also provided for convenience.
	
>>> dir(fractions.operator)
['__abs__', '__add__', '__and__', '__concat__', '__contains__', '__delitem__', '__doc__', 
'__eq__', '__floordiv__', '__ge__', '__getitem__', '__gt__', '__iadd__', '__iand__', 
'__iconcat__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__', '__index__', 
'__inv__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__itruediv__', 
'__ixor__', '__le__', '__loader__', '__lshift__', '__lt__', '__mod__', '__mul__', '__name__'
, '__ne__', '__neg__', '__not__', '__or__', '__package__', '__pos__', '__pow__', 
'__rshift__', '__setitem__', '__sub__', '__truediv__', '__xor__', '_compare_digest', 'abs', 
'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf', 'delitem', 'eq', 'floordiv', 
'ge', 'getitem', 'gt', 'iadd', 'iand', 'iconcat', 'ifloordiv', 'ilshift', 'imod', 'imul', 
'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift', 'is_', 'is_not', 'isub', 
'itemgetter', 'itruediv', 'ixor', 'le', 'lshift', 'lt', 'methodcaller', 'mod', 'mul', 'ne', 
'neg', 'not_', 'or_', 'pos', 'pow', 'rshift', 'setitem', 'sub', 'truediv', 'truth', 'xor']	

>>> fractions.operator.add(1,2)
3

(6) random库

>>> import random
>>> help(random)
Help on module random:

NAME
    random - Random variable generators.

DESCRIPTION
        integers
        --------
               uniform within range
    
        sequences
        ---------
               pick random element
               pick random sample
               generate random permutation
    
        distributions on the real line:
        ------------------------------
               uniform
               triangular
               normal (Gaussian)
               lognormal
               negative exponential
               gamma
               beta
               pareto
               Weibull
    
        distributions on the circle (angles 0 to 2pi)
        ---------------------------------------------
               circular uniform
               von Mises
    
    General notes on the underlying Mersenne Twister core generator:
    
    * The period is 2**19937-1.
    * It is one of the most extensively tested generators in existence.
    * The random() method is implemented in C, executes in a single Python step,
      and is, therefore, threadsafe.

CLASSES
    _random.Random(builtins.object)
        Random
            SystemRandom
    
    class Random(_random.Random)
     |  Random number generator base class used by bound module functions.
     |  
     |  Used to instantiate instances of Random to get generators that don't
     |  share state.
     |  
     |  Class Random can also be subclassed if you want to use a different basic
     |  generator of your own devising: in that case, override the following
     |  methods:  random(), seed(), getstate(), and setstate().
     |  Optionally, implement a getrandbits() method so that randrange()
     |  can cover arbitrarily large ranges.
     |  
     |  Method resolution order:
     |      Random
     |      _random.Random
     |      builtins.object
	 
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 
'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__'
, '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', 
'__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi', '_random', 
'_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 
'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 
'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 
'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 
'weibullvariate']

>>> help(random.shuffle)
Help on method shuffle in module random:

shuffle(self, x, random=None) method of random.Random instance
    x, random=random.random -> shuffle list x in place; return None.
    
    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.
	
>>> list(range(10));
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(_)
>>> _
[6, 2, 3, 9, 7, 0, 4, 1, 5, 8]

(7) array库

>>> import array
>>> help(array)
Help on built-in module array:

NAME
    array

DESCRIPTION
    This module defines an object type which can efficiently represent
    an array of basic values: characters, integers, floating point
    numbers.  Arrays are sequence types and behave very much like lists,
    except that the type of objects stored in them is constrained.  The
    type is specified at object creation time by using a type code, which
    is a single character.  The following type codes are defined:
    
        Type code   C Type             Minimum size in bytes 
        'b'         signed integer     1 
        'B'         unsigned integer   1 
        'u'         Unicode character  2 (see note) 
        'h'         signed integer     2 
        'H'         unsigned integer   2 
        'i'         signed integer     2 
        'I'         unsigned integer   2 
        'l'         signed integer     4 
        'L'         unsigned integer   4 
        'q'         signed integer     8 (see note) 
        'Q'         unsigned integer   8 (see note) 
        'f'         floating point     4 
        'd'         floating point     8 
    
    NOTE: The 'u' typecode corresponds to Python's unicode character. On 
    narrow builds this is 2-bytes on wide builds this is 4-bytes.
    
    NOTE: The 'q' and 'Q' type codes are only available if the platform 
    C compiler used to build Python supports 'long long', or, on Windows, 
    '__int64'.
    
    The constructor is:
    
    array(typecode [, initializer]) -- create a new array

CLASSES
    builtins.object
        array
    
    ArrayType = class array(builtins.object)
     |  array(typecode [, initializer]) -> array
     |  
     |  Return a new array whose items are restricted by typecode, and
     |  initialized from the optional initializer value, which must be a list,
     |  string or iterable over elements of the appropriate type.
     |  
     |  Arrays represent basic values and behave very much like lists, except
     |  the type of objects stored in them is constrained.
	 
>>> dir(array)
['ArrayType', '__doc__', '__loader__', '__name__', '__package__', '_array_reconstructor', 
'array', 'typecodes']

>>> dir(array.array)
['__add__', '__class__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', 
'__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', 
'__subclasshook__', 'append', 'buffer_info', 'byteswap', 'count', 'extend', 'frombytes', 
'fromfile', 'fromlist', 'fromstring', 'fromunicode', 'index', 'insert', 'itemsize', 'pop', 
'remove', 'reverse', 'tobytes', 'tofile', 'tolist', 'tostring', 'tounicode', 'typecode']

>>> array.array('b', range(10)).fromlist(list(range(2)))
>>> _
array('b', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> array.array('b', range(5)).fromlist(list(range(10)))
>>> _
array('b', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> _.reverse()
>>> _
array('b', [9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> _.tostring()
b'\t\x08\x07\x06\x05\x04\x03\x02\x01\x00'

因为接下来我会专门开一个系列来从头学数学,所以这些数学函数现在没必要展开来讲,迟早会全部用上。这里只要知道有这些函数工具就可以了。

本节到此结束。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值