阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Python math 与 cmath 模块概述

28次阅读
没有评论

共计 1898 个字符,预计需要花费 5 分钟才能阅读完成。

导读 Python math 模块提供了许多对浮点数的数学运算函数。Python cmath 模块包含了一些用于复数运算的函数。

Python math 与 cmath 模块概述

cmath 模块的函数跟 math 模块函数基本一致,区别是 cmath 模块运算的是复数,math 模块运算的是数学运算。

要使用 math 或 cmath 函数必须先导入:

import math

查看 math 查看包中的内容:

>>> import math
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>>

各个函数解析:
Python math 与 cmath 模块概述

Python 复数的支持和 cmath 模块应用

Python 提供对于复数运算的支持,复数在 Python 中的表达式为 C==c.real+c.imag*j,复数 C 由他的实部和虚部组成。

对于复数,Python 支持它的加减乘除运算,同时提供了 cmath 模块对其他复杂运算进行支持。cmath 模块和 Python 中的 math 模块对应,math 提供对于实数的支持,在这里主要讨论 cmath 模块中的几个函数的用法。

查看 cmath 查看包中的内容

>>> import cmath
>>> dir(cmath)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>>
1. 极坐标和笛卡尔坐标表示的转换。

C==c.real+c.imag*j 的复数表示方法为复数的笛卡尔表示法,cmath 模块中的 polar() 方法和 rect() 方法可以对复数进行极坐标表示和笛卡尔表示方法的转换。例:

>>> import cmath
>>> Z=1+2j
>>> print cmath.polar(Z)
(2.23606797749979, 1.1071487177940904)
>>> a,b=cmath.polar(Z)
>>> print cmath.rect(a,b)
(1+2j)
>>>

polar 函数对一个输入的笛卡尔形势的复数进行计算,输出为一个二元组,第一个值为 Z 的模值,第二个为幅度值。rect() 函数对输入的模和幅度值进行计算输出笛卡尔表示。

如果需要单独对一个复数进行幅度值的求解,可以调用 cmath.phrase(x) 函数,返回幅度值。

2. 复数的幂指数与对数函数

复数的指数函数为 cmath.exp(x), 用来求解 e^x 表达式。

cmath.log(x[,base]) 用来求以 Base 为底的 x 的对数。

cmath.log10(x) 用来求以 10 为底 x 的对数

cmath.sqrt(x) 用来求 x 的平方根。

3. 复数的三角函数方程

包括所有的三角函数计算 acos(x) asin(x) atan(x) sin(x) cos(x) tan(x)。

4. 参数类判断

cmath.isinf(x) 如果 x 的实部或者虚部为无穷大,则返回 true。

cmath.isnan(x) 如果 x 的实部或者虚步不是数字则返回 true。

5. 常量支持

cmat.pi 浮点值,表示圆周率的大小

cmat.e 浮点值,表示自然对数的底

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计1898字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中