Python之基础02-变量那些小事-数字

Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

F:\软件\PowerCmd>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a=34
>>> type(a)
<type 'int'>
>>> a=3.89
>>> type(a)
<type 'float'>
>>> a="hello python"
>>> type(a)
<type 'str'>
>>> a=[1,2,3]
>>> type(a)
<type 'list'>
#查看a的属性和方法
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> a.count(1)
1
>>> a=[1,1,1,3,4]
>>> a.count(1)
3
>>> 
>>> a.__class__
<type 'list'>
>>> type(a)
<type 'list'>
>>> a.__doc__
"list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"
>>> 

Python是完全面向对象的语言,一切皆对象,对象是类的实例化,面向对象语言的三大特性:封装,继承,多态,在Python中一切的变量都是对象

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.3*3
0.8999999999999999
>>> 0.3/3
0.09999999999999999
>>> 3//10
0
>>> 10//3
3
>>> 3/10
0
>>> 10/3
3
>>> 10.0/3
3.3333333333333335
>>> print 0.3*3
0.9
>>> print 0.3/3
0.1
>>> from decimal import Decimal as D
>>> D('0.3')*D(3)
Decimal('0.9')
>>> print D('0.3')*D(3)
0.9
>>> D('0.3')/D(3)
Decimal('0.1')
>>> print D('0.3')/D(3)
0.1
>>> 

对于数字,跟其他的编程语言没什么特别的,加减乘除基本的差不多下面介绍点特别的:
如上面对的代码实例:
“//”:这个双斜杠在Python中代表整除
由于计算精确度的原因,导致0.3*3或者0.3/3出现不正确的清楚,解决方式有两种:
第一种方式用print打印,因为print设计输入比较人性化,
第二种方式是引入decimal跟Java中的类似,引入方式:from decimal import Decimal as D 从decimal这个库中引入Decimal这函数或者叫做方法,取个别名叫做 D,用这个函数就直接用别名,这样就方便我们使用了;
当然引入Decimal还是有其缺点的就是计算的时间大大增加看如下的代码比较:

F:\软件\PowerCmd>python -mtimeit -s "from decimal import Decimal as D" "1.2+3.4"
10000000 loops, best of 3: 0.0403 usec per loop

F:\软件\PowerCmd>python -mtimeit -s "from decimal import Decimal as D" "float('1.2')+float('3.4')"
1000000 loops, best of 3: 0.988 usec per loop

F:\软件\PowerCmd>python -mtimeit -s "from decimal import Decimal as D" "D('1.2')+D('3.4')"
10000 loops, best of 3: 62.9 usec per loop

Python数字涉及的常用的两个库math和random
直接上代码展示应用:
math

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
#开方
>>> math.sqrt(81)
9.0
#取对数
>>> math.log10(10**30)
30.0
#math.pow(x,y) 计算 x的y次方
>>> math.pow(2,10)
1024.0
#math.factorial(x)计算x的阶乘
>>> math.factorial(5)
120
>>> math.factorial(4)
24
#一切皆对象,所以导入的库也可以看做是一个对象,可以查看它的属性和方法
>>> dir(math)
['__doc__', '__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', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
#获取库的帮助文档 windows下使用是空格键或者enter键查看,退出按q
>>> help(math)
Help on built-in module math:

NAME
    math

FILE
    (built-in)

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)

        Return the arc cosine (measured in radians) of x.

    acosh(...)
        acosh(x)

        Return the inverse hyperbolic cosine of x.

    asin(...)
        asin(x)

        Return the arc sine (measured in radians) of x.

    asinh(...)
        asinh(x)

        Return the inverse hyperbolic sine of x.

    atan(...)
        atan(x)

        Return the arc tangent (measured in radians) of x.

    atan2(...)
        atan2(y, x)

        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.

    atanh(...)
        atanh(x)

        Return the inverse hyperbolic tangent of x.

    ceil(...)
        ceil(x)

        Return the ceiling of x as a float.
        This is the smallest integral value >= x.

    copysign(...)
        copysign(x, y)

        Return x with the sign of y.

    cos(...)
        cos(x)

        Return the cosine of x (measured in radians).

    cosh(...)
        cosh(x)

        Return the hyperbolic cosine of x.

    degrees(...)
        degrees(x)

        Convert angle x from radians to degrees.

    erf(...)
        erf(x)

        Error function at x.

    erfc(...)
        erfc(x)

        Complementary error function at x.

    exp(...)
        exp(x)

        Return e raised to the power of x.

    expm1(...)
        expm1(x)

        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.

    fabs(...)
        fabs(x)

        Return the absolute value of the float x.

    factorial(...)
        factorial(x) -> Integral

        Find x!. Raise a ValueError if x is negative or non-integral.

    floor(...)
        floor(x)

        Return the floor of x as a float.
        This is the largest integral value <= x.

    fmod(...)
        fmod(x, y)

        Return fmod(x, y), according to platform C.  x % y may differ.

    frexp(...)
        frexp(x)

        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.

    fsum(...)
        fsum(iterable)

        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.

    gamma(...)
        gamma(x)

        Gamma function at x.

    hypot(...)
        hypot(x, y)

        Return the Euclidean distance, sqrt(x*x + y*y).

    isinf(...)
        isinf(x) -> bool

        Check if float x is infinite (positive or negative).

    isnan(...)
        isnan(x) -> bool

        Check if float x is not a number (NaN).

    ldexp(...)
        ldexp(x, i)

        Return x * (2**i).

    lgamma(...)
        lgamma(x)

        Natural logarithm of absolute value of Gamma function at x.

    log(...)
        log(x[, base])

        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.

    log10(...)
        log10(x)

        Return the base 10 logarithm of x.

    log1p(...)
        log1p(x)

        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.

    modf(...)
        modf(x)

        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.

    pow(...)
        pow(x, y)

        Return x**y (x to the power of y).

    radians(...)
        radians(x)

        Convert angle x from degrees to radians.

    sin(...)
        sin(x)

        Return the sine of x (measured in radians).

    sinh(...)
        sinh(x)

        Return the hyperbolic sine of x.

    sqrt(...)
        sqrt(x)

        Return the square root of x.

    tan(...)
        tan(x)

        Return the tangent of x (measured in radians).

    tanh(...)
        tanh(x)

        Return the hyperbolic tangent of x.

    trunc(...)
        trunc(x:Real) -> Integral

        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    pi = 3.141592653589793
>>> 

random

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
>>> random.random()
0.7644452090557221
>>> random.random()
0.9748845803332888
>>> random.random()
0.9835634630711295
#随机概率问题,可以用来判断中奖几率
>>> random.random()>0.8
False
>>> random.random()>0.8
True
>>> random.random()>0.8
True
>>> random.random()>0.8
False
>>> random.random()>0.8
False
>>> random.random()>0.8
False
>>> random.random()>0.8
False
>>> random.random()>0.8
False
#random.choice从序列中获取一个随机元素。其函数原型为:#random.choice(sequence)。参数sequence表示一个有序类型。这里要说
#明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。#list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据#模型这一章。下面是使用choice的一些例子:
#print random.choice("学习Python")   
#print random.choice(["JGood", "is", "a", "handsome", "boy"])  
#print random.choice(("Tuple", "List", "Dict"))  
>>> random.choice([1,2,3,4,5,6,7,8,9])
2
>>> random.choice([1,2,3,4,5,6,7,8,9])
8
>>> random.choice([1,2,3,4,5,6,7,8,9])
1
#random.randint()的函数原型为:random.randint(a, b),用于生成一
#个指定范围内的整数。其中参数a是下限,参数b是上限,
#生成的随机数n: a <= n <= b
>>> random.randint(1,10)
5
>>> random.randint(1,10)
7
>>> random.randint(1,10)
1
#random.uniform的函数原型为:random.uniform(a, b),用于生成一个
#指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。
#如果a < b,则生成的随机数n: a <= n <= b。如果 a >b, 
#则 b <= n <= a。
>>> random.uniform(1,10)
6.687105373886521
>>> random.uniform(1,10)
2.38018207089072
>>> random.uniform(1,10)
4.449608676476761
#随机生成符合高斯分布的随机数,random.guass(mu(均值),lamda(方差))mu(均值),lamda(方差)为高斯分布的两个参数。
>>> random.gauss(0,0.5)
-0.8243955660165138
## 从序列中随机挑选k个元素
>>> random.sample([1,2,3,4,5,6,7,8,9],3)
[9, 6, 8]
>>> random.sample([1,2,3,4,5,6,7,8,9],3)
[7, 1, 6]
>>> random.sample([1,2,3,4,5,6,7,8,9],3)
[3, 5, 2]
#将序列的所有元素随机排序
>>> s=[1,2,3,4,5,6,7,8,9]
>>> random.shuffle(s)
>>> s
[8, 3, 7, 5, 2, 6, 9, 4, 1]
>>> random.shuffle(s)
>>> s
[8, 3, 2, 7, 6, 1, 5, 9, 4]
#random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
>>> random.randrange(10,100,2)
74
>>> random.randrange(10,100,2)
46
>>> random.randrange(10,100,2)
56
>>> 

还有比较专业的库:numpy,scipy
numpy:产生数字或者矩阵,正态分布的随机数,矩阵求逆,转支等操作
scipy:拟合,线性差值,样条差值,积分,微分,解非线性方程,滤波器的设计

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值