Table of contents
number crunching
=
: used to assign values to variablestype(x)
: View the type of dataisinstance(x, A_tuple)
: Determine whether the data is the expected type+
: add two numbers-
: Subtract two numbers*
: Multiply two numbers/
: Divide two numbers%
: Two numbers carry on the remainder**
: Two numbers are exponentiated
# 给变量赋值数字类型数据
int_data = 100 # 整数 int
float_data = 8.88 # 小数 float
complex_data = 3+5j # 复数 complex
# 查看变量所属数据类型
print(type(int_data)) # <class 'int'>
print(type(float_data)) # <class 'float'>
print(type(complex_data)) # <class 'complex'>
# 判断两个数据的类型是否相等
print(isinstance(int_data, int)) # True
print(isinstance(float_data, int)) # False
# 加
print(2 + 1) # 3
print(2 + 6.6) # 8.6 整数和浮点数运算结果为浮点数
print(2.1 + 1.2) # 3.3
# 减
print(2 - 1) # 1
print(2 - 6.6) # -4.6
print(2.1 - 1.2) # 0.9000000000000001
print(round(2.1 - 1.2, 1)) # 0.9
# 乘
print(2 * 1) # 2
print(2 * 6.6) # 13.2
print(2.1 * 1.2) # 2.52
# 除
print(2 / 1) # 2.0
print(6.66 / 2) # 3.33
print(6.66 / 2.22) # 3.0
# 求余
print(10 % 3) # 1
print(20.22 % 3) # 2.219999999999999
# 幂运算
print(5 ** 2) # 5的平方,25
print(2 ** 7) # 2的7次方,128
type conversion
int(x, base=10)
: Convert a string or number to an integer. x is a string or a number, base is a base number, and the default is base 10.float(x)
: Convert a string or number to a floating point number. x is a string or integer.
# int()
# 不传参数则为0
int() # 0
# 将字符串转为整数
int("666") # 666
# 向下取整
int(6.66) # 6
# 将数字转为8进制
int('12',8) # 10
# flaot()
# 不传参数则为0.0
flaot() # 0.0
# 将字符串转为浮点数
float("6.88") # 6.88
Note: If there are non-numeric characters in the converted content, an error will be reported.
math function
function | illustrate |
---|---|
abs(x) |
Returns the absolute value of a number. x is a numeric expression. |
max(x) |
Returns the maximum value of the given argument, which can be a sequence. |
min(x) |
Returns the minimum value of the given argument, which can be a sequence. |
pow(x, y, z) |
Returns the value of x raised to the yth power. Modulo the result if z exists, equivalent to pow(x,y) %z |
round(number, digits) |
Returns the rounded decimal number with digits reserved. If digits is not filled, it defaults to an integer |
Example usage:
abs(-2.66) # 2.66
max(1, 2, 3) # 3
max([6, 7, 8]) # 8
min(1, 2, 3) # 1
pow(10,2) # 100
pow(10,2,3) # 1
round(5.68) # 6
round(5.64, 1) # 5.6
Mathematics library math, cmath
math
: The module provides many mathematical operation functions on floating-point numbers.cmath
: The module contains some functions for complex arithmetic.
See what's included in math:
import math
print(dir(math))
# 打印内容
[
'__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__',
'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2',
'atanh', 'ceil', 'comb',
'copysign', 'cos', 'cosh',
'degrees', 'dist', 'e',
'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp',
'fsum', 'gamma', 'gcd',
'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan',
'isqrt', 'ldexp', 'lgamma',
'log', 'log10', 'log1p',
'log2', 'modf', 'nan',
'perm', 'pi', 'pow',
'prod', 'radians', 'remainder',
'sin', 'sinh', 'sqrt',
'tan', 'tanh', 'tau',
'trunc'
]
math module constants
constant | illustrate |
---|---|
math.e |
Returns Euler's number (2.7182...) |
math.inf |
Returns a positive infinity floating point number |
math.nan |
Returns a floating point value NaN (not a number) |
math.pi |
π generally refers to pi. PI (3.1415…) |
math.tau |
The mathematical constant τ = 6.283185…, to the available precision. Tau is a circular constant equal to 2π, the ratio of the circumference of a circle to its radius. |
math module methods
function | illustrate |
---|---|
math.acos(x) |
Returns the arccosine of x in the range 0 to pi. |
math.acosh(x) |
Returns the inverse hyperbolic cosine of x. |
math.asin(x) |
Returns the arcsine of x in the range -pi/2 to pi/2. |
math.asinh(x) |
Returns the inverse hyperbolic sine of x. |
math.atan(x) |
Returns the arctangent of x in the range -pi/2 to pi/2. |
math.atan2(y, x) |
Returns the arctangent of the given X and Y coordinate values, the result is between -pi and pi. |
math.atanh(x) |
Returns the inverse hyperbolic tangent of x. |
math.ceil(x) |
round x up to the nearest integer |
math.comb(n, k) |
Returns the total number of ways to select k items from n items without repetition and in no order. |
math.copysign(x, y) |
Returns a floating point number based on the absolute value of x and the sign of y. |
math.cos() |
Returns the cosine of x in radians. |
math.cosh(x) |
Returns the hyperbolic cosine of x. |
math.degrees(x) |
Convert the angle x from radians to degrees. |
math.dist(p, q) |
Returns the Euclidean distance between the two points p and q, given as a sequence (or iterable) of coordinates. Both points must have the same dimensions. |
math.erf(x) |
Returns an error function for a number |
math.erfc(x) |
returns the complementary error function at x |
math.exp(x) |
Returns e raised to the power of x, Ex, where e = 2.718281… is the base of natural logarithms. |
math.expm1() |
Returns Ex - 1, e raised to the power of x, Ex, where e = 2.718281… is the base of the natural logarithm. This is usually more precise than math.e ** x or pow(math.e, x) . |
math.fabs(x) |
Returns the absolute value of x. |
math.factorial(x) |
Returns the factorial of x. ValueError is raised if x is not an integer or is negative. |
math.floor() |
rounds a number down to the nearest integer |
math.fmod(x, y) |
returns the remainder of x/y |
math.frexp(x) |
Returns the mantissa and exponent of x as a (m, e) pair. m is a float and e is an integer, exactly x == m * 2**e . Returns (0.0, 0) if x is zero, otherwise 0.5 <= abs(m) < 1. |
math.fsum(iterable) |
Returns the sum of elements in an iterable (tuple, array, list, etc.), as a floating point value. |
math.gamma(x) |
Returns the gamma function value at x. |
math.gcd() |
Returns the greatest common divisor of the given integer arguments. |
math.hypot() |
Returns the Euclidean norm, sqrt(sum(x**2 for x in coordinates)). This is the length of the vector from the origin to the point given by the coordinates. |
math.isclose(a,b *,rel_tol=1e-09,abs_tol=0.0) |
Checks if two values are close to each other, returns True if a and b have close values, otherwise returns False. |
math.isfinite(x) |
Determines whether x is finite, and returns True if x is neither infinite nor NaN, otherwise returns False. |
math.isinf(x) |
Determines whether x is infinite, and returns True if x is positive or negative infinity, otherwise returns False. |
math.isnan() |
Determines whether a number is NaN, and returns True if x is NaN (not a number), otherwise returns False. |
math.isqrt() |
Rounds the square root number down to the nearest integer. |
math.ldexp(x, i) |
Returns x * (2**i) . This is basically the inverse of the function math.frexp(). |
math.lgamma() |
Returns the natural logarithm of the absolute value of the gamma function at x. |
math.log(x[, base]) |
使用一个参数,返回 x 的自然对数(底为 e )。 |
math.log10(x) |
返回 x 底为 10 的对数。 |
math.log1p(x) |
返回 1+x 的自然对数(以 e 为底)。 |
math.log2(x) |
返回 x 以 2 为底的对数 |
math.perm(n, k=None) |
返回不重复且有顺序地从 n 项中选择 k 项的方式总数。 |
math.pow(x, y) |
将返回 x 的 y 次幂。 |
math.prod(iterable) |
计算可迭代对象中所有元素的积。 |
math.radians(x) |
将角度 x 从度数转换为弧度。 |
math.remainder(x, y) |
返回 IEEE 754 风格的 x 除于 y 的余数。 |
math.sin(x) |
返回 x 弧度的正弦值。 |
math.sinh(x) |
返回 x 的双曲正弦值。 |
math.sqrt(x) |
返回 x 的平方根。 |
math.tan(x) |
返回 x 弧度的正切值。 |
math.tanh(x) |
返回 x 的双曲正切值。 |
math.trunc(x) |
返回 x 截断整数的部分,即返回整数部分,删除小数部分 |
使用示例:
import math
math.ceil(5.4) # 6
math.ceil(5.5) # 6
math.fabs(-6) # 6.0
math.fabs(6) # 6.0
math.floor(6.9) # 6
math.fmod(5, 2) # 1.0
math.isclose(8.005, 8.450, abs_tol = 0.4) # False
math.isclose(8.005, 8.450, abs_tol = 0.5) # True
print(0.1+0.2) # 0.30000000000000004
math.isclose(0.1+0.2, 0.3) #True
math.isnan(float("NaN")) # True
math.pow(2, 10) # 1024.0
math.sqrt(25) # 5.0
随机函数库 random
查看random中包含的内容:
import random
print(dir(random))
# 打印内容
[
'BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set',
'__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', '_accumulate',
'_acos', '_bisect', '_ceil', '_cos', '_e',
'_exp', '_inst', '_log', '_os', '_pi',
'_random', '_repeat', '_sha512', '_sin', '_sqrt',
'_test', '_test_generator', '_urandom', '_warn', 'betavariate',
'choice', 'choices', 'expovariate', 'gammavariate', 'gauss',
'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate',
'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate',
'weibullvariate'
]
random 模块方法
函数 | 说明 |
---|---|
seed() |
初始化随机数生成器。 |
getstate() |
返回捕获生成器当前内部状态的对象。 |
setstate() |
state 应该是从之前调用 getstate() 获得的,并且 setstate() 将生成器的内部状态恢复到 getstate() 被调用时的状态。 |
getrandbits(k) |
返回具有 k 个随机比特位的非负 Python 整数。 此方法随 MersenneTwister 生成器一起提供,其他一些生成器也可能将其作为 API 的可选部分提供。 在可能的情况下,getrandbits() 会启用 randrange() 来处理任意大的区间。 |
randrange() |
从 range(start, stop, step) 返回一个随机选择的元素。 |
randint(a, b) |
返回随机整数 N 满足 a <= N <= b。 |
choice(seq) |
从非空序列 seq 返回一个随机元素。 如果 seq 为空,则引发 IndexError。 |
choices(population, weights=None, *, cum_weights=None, k=1) |
从 population 中选择替换,返回大小为 k 的元素列表。 如果 population 为空,则引发 IndexError。 |
shuffle(x[, random]) |
将序列 x 随机打乱位置。 |
sample(population, k, *, counts=None) |
返回从总体序列或集合中选择的唯一元素的 k 长度列表。 用于无重复的随机抽样。 |
random() |
返回 [0.0, 1.0) 范围内的下一个随机浮点数。 |
uniform(x, y) |
随机生成下一个实数,它在[x,y]范围内。 |
triangular(low, high, mode) |
返回一个随机浮点数 N ,使得 low <= N <= high 并在这些边界之间使用指定的 mode 。 low 和 high 边界默认为零和一。 mode 参数默认为边界之间的中点,给出对称分布。 |
betavariate(alpha, beta) |
Beta 分布。 参数的条件是 alpha > 0 和 beta > 0。 返回值的范围介于 0 和 1 之间。 |
expovariate(lambd) |
指数分布。 lambd 是 1.0 除以所需的平均值,它应该是非零的。 |
gammavariate() |
Gamma 分布( 不是伽马函数) 参数的条件是 alpha > 0 和 beta > 0。 |
gauss(mu, sigma) |
Gamma 分布( 不是伽马函数) 参数的条件是 alpha > 0 和 beta > 0。 |
lognormvariate(mu, sigma) |
对数正态分布。 如果你采用这个分布的自然对数,你将得到一个正态分布,平均值为 mu 和标准差为 sigma 。 mu 可以是任何值,sigma 必须大于零。 |
normalvariate(mu, sigma) |
正态分布。 mu 是平均值,sigma 是标准差。 |
vonmisesvariate(mu, kappa) |
冯·米塞斯分布。 mu 是平均角度,以弧度表示,介于0和 2*pi 之间,kappa 是浓度参数,必须大于或等于零。 |
paretovariate(alpha) |
帕累托分布。 alpha 是形状参数。 |
weibullvariate(alpha, beta) |
威布尔分布。 alpha 是比例参数,beta 是形状参数。 |
使用示例:
import random
# 从1-100中选一个整数
print(random.randint(1,100)) # 80
print(random.choice([1, 2, 3, 5, 9])) # 2
print(random.choice('A String')) # A
print(random.choice(range(10))) # 8
# 从 1-100 中选取一个奇数
print(random.randrange(1, 100, 2)) # 57
# 从 0-99 选取一个随机数
print(random.randrange(100)) # 91
# 随机选取0到100间的偶数
print(random.randrange(0, 101, 2)) # 22
print(random.random()) # 0.699045676948276
print(random.uniform(1, 100)) # 66.79353123577998
保留小数到指定位数
# 向下取整,转为整数
print(int(58.86)) # 58
import math
# 向上取整,转为整数
print(math.ceil(58.86)) # 59
# 四舍五入,转为整数
print(round(58.86)) # 59
# 四舍五入,保留2位小数
print(round(4.859999999999999, 2)) # 4.86
# 分割整数和小数
print(str(58.866).split(".")[0]) # 58
三角函数
函数 | 说明 |
---|---|
acos(x) |
返回x的反余弦弧度值。 |
asin(x) |
返回x的反正弦弧度值。 |
atan(x) |
返回x的反正切弧度值。 |
atan2(y, x) |
返回给定的 X 及 Y 坐标值的反正切值。 |
cos(x) |
返回x的弧度的余弦值。 |
hypot(x, y) |
返回欧几里德范数 sqrt(xx + yy)。 |
sin(x) |
返回的x弧度的正弦值。 |
tan(x) |
返回x弧度的正切值。 |
degrees(x) |
将弧度转换为角度,如degrees(math.pi/2) , 返回90.0。 |
radians(x) |
将角度转换为弧度。 |