math模块的使用

math模块
  • .ceil() —— 以浮点数的方式返回向上圆整的结果

    >>> math.ceil(1.23)
    2
    
  • .floor() —— 以浮点数的方式返回向下圆整的结果

    >>> math.floor(2.13)
    2
    
  • .sqrt() —— 返回平方根;不能用于复数

    >>> math.sqrt(9)
    3.0
    -----------------
    >>> math.sqrt(-3)
    Traceback (most recent call last):
      File "<pyshell#8>", line 1, in <module>
        math.sqrt(-3)
    ValueError: math domain error
    

    在有些平台上可能会是:

    >>> math.sqrt(-3)
    nan
    

    注:nan具有特殊含义,指的是“not a number”

  • .log(b, a) —— 以a为底,b为真数的对数

    >>> math.log(10,10)
    1.0
    >>> math.e
    2.718281828459045
    >>> math.log(10,math.e)
    2.302585092994046
    

    其中,math.e 即为数学中的自然数e
    引入异常处理机制:

    import math
    try:
        a = eval(input('请输入底数:'))
        b = eval(input('请输入真数:'))
        c = math.log(b, a)
    except ValueError:
        if a <= 0 and b > 0:
            print('底数不能小于等于0')
        elif b <= 0 and a > 0:
            print('真数不能小于等于0')
        elif a <= 0 and b <= 0:
            print('真数和底数都不能小于等于0')
    except ZeroDivisionError:
        print('底数不能为1')
    except NameError:
        print('输入必须为实数')
    else:
        print(c)
    
  • .gcd(a, b) —— 求最大公约数

    >>> math.gcd(4, 6)
    2
    

    等价于

    def gcd(a, b):
    	return (a if b == 0 else gcd(b, a % b))
    
  • .factorial(n) —— 求阶乘n!

    >>> import math
    >>> math.factorial(3)
    6
    >>> math.factorial(0)
    1
    
cmath模块

正如介绍sqrt时所示,用sqrt处理复数会出错。

  • cmath是Python标准库专门用于处理复数的模块。

  • 在处理复数的开方运算时,因为结果是复数,math会报错,应使用cmath模块处理负数开方运算

    >>> import cmath
    >>> cmath.sqrt(-1)
    1j
    
    >>> math.sqrt(-10)
    Traceback (most recent call last):
      File "<pyshell#11>", line 1, in <module>
        math.sqrt(-10)
    ValueError: math domain error
    
    >>> cmath.sqrt(-10)
    3.1622776601683795j
    

注:应避免使用from…import…而采用math.sqrt或camth.sqrt的方法调用,若math与cmath均使用此方法导入模块,将无法使用常规sqrt,这是很隐蔽的名称冲突。
Python没有专门表示虚数的类型,而是将虚数视为实部为零的复数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值