• Python数字类型及数学运算


    1、数字类型分为int、float和complex,complex暂时用不到,int和float的相关运算和类型转换如下:

    >>> 59+12
    71
    >>> 59-12
    47
    >>> 2*19
    38
    >>> 2**5
    32
    >>> 19/2
    9.5
    >>> 19//2
    9
    >>> 19%2
    1
    >>> 3*4.5-6 #自动类型转换
    7.5
    >>> x=4.5 #强制类型转换
    >>> int(x)
    4
    >>> x='30'
    >>> int(x)
    30
    >>> x='4.5'
    >>> float(x)
    4.5
    >>> x='4.5' #转一次ok,想要自动转2次报错
    >>> int(x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '4.5'
    

     2、常量:

    >>> math.pi
    3.141592653589793
    >>> math.e
    2.718281828459045
    

    3、数学函数:

    >>> import math
    >>> math.ceil(4.5)
    5
    >>> math.floor(4.5)
    4
    >>> math.fabs(-4.5)
    4.5
    >>> math.fabs(10)
    10.0
    >>> max(3,100,301,200)#求最大值最小值
    301
    >>> min(3,100,301,200)
    3
    >>> math.factorial(2) #factorial,阶乘
    2
    >>> math.factorial(3)
    6
    >>> math.gcd(17,51)#返回能被两个参数整除的最大正整数
    17
    >>> math.gcd(256,128)
    128
    >>> math.ldexp(2,3)#已知尾数和指数的情况下,计算方程x=m*2^n
    16.0
    >>> math.frexp(16)#回退给定数值的尾数和指数,m介于0,1之间
    (0.5, 5)
    >>> math.frexp(15)
    (0.9375, 4)
    >>> math.exp(10)#x=e^n
    22026.465794806718
    >>> math.log(math.e)#默认一个参数,base=e
    1.0
    >>> math.log(16,2)#可输入两个参数,第二个参数是base
    4.0
    >>> math.log2(8)#以2为底的默认方法
    3.0
    >>> math.pow(3,4)#计算幂,转换成float
    81.0
    >>> math.sqrt(256)#开平方根
    16.0
    >>> x=math.pi #四舍五入
    >>> x
    3.141592653589793
    >>> round(x,2)
    3.14
    
  • 相关阅读:
    汉斯·季默:布拉格现场
    天使在美国第二部:重建
    欢迎访问我的独立博客 tracefact.net (2019.1.30)
    Kafka 分布式消息系统
    Webpack入门
    《.NET之美》消息及勘误
    MacBook笔记本微信视频聊天没有声音怎么办?
    libnuma.so.1()(64bit) is needed by mysql-community-server-5.7.9-1.el6.x86_64
    List stream 对象 属性去重
    JS遍历对象的方式
  • 原文地址:https://www.cnblogs.com/rhyswang/p/8133751.html
Copyright © 2020-2023  润新知