python math模块详解

math — Mathematical functions

数论与表示函数

  • math.ceil(x)

    返回 x 的向上取整,即大于或者等于 x 的最小整数。

    如果 x 不是一个浮点数,则委托 x.__ceil__(), 返回 Integral 类的值。

  • math.copysign(x, y)

    返回一个基于 x 的绝对值和 y 的符号的浮点数。

    copysign(1.0, -0.0) 返回 -1.0.

  • math.fabs(x)

    返回 x 的绝对值。

  • math.factorial(x)

    以一个整数返回 x 的阶乘。

    如果 x 不是整数或为负数时则将引发 ValueError

  • math.floor(x)

    返回 x 的向下取整,小于或等于 x 的最大整数。

    如果 x 不是浮点数,则委托 x.__floor__() ,它应返回 Integral 值。

  • math.fmod(x, y)

    返回 fmod(x, y) ,由平台C库定义。请注意,Python表达式 x % y 可能不会返回相同的结果。C标准的目的是 fmod(x, y) 完全(数学上;到无限精度)等于 x - n*y 对于某个整数 n ,使得结果具有 与 x 相同的符号和小于 abs(y) 的幅度。Python的 x % y 返回带有 y 符号的结果,并且可能不能完全计算浮点参数。

    例如, fmod(-1e-100, 1e100)-1e-100 ,但Python的 -1e-100 % 1e100 的结果是 1e100-1e-100 ,它不能完全表示为浮点数,并且取整为令人惊讶的 1e100

    出于这个原因,函数 fmod() 在使用浮点数时通常是首选,而Python的 x % y 在使用整数时是首选。

  • math.frexp(x)

    返回 x 的尾数和指数作为对(m, e)m 是一个浮点数, e 是一个整数,正好是 x == m * 2**e

    如果 x 为零,则返回 (0.0, 0) ,否则返回 0.5 <= abs(m) < 1

    这用于以可移植方式“分离”浮点数的内部表示。

  • math.fsum(iterable)

    返回迭代中的精确浮点值。通过跟踪多个中间部分和来避免精度损失

    >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
    0.9999999999999999
    >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
    1.0
    
  • math.gcd(a, b)

    返回整数 ab 的最大公约数。如果 ab 之一非零,则 gcd(a, b) 的值是能同时整除 ab 的最大正整数。gcd(0, 0) 返回 0

  • math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

    ab 的值比较接近则返回 True,否则返回 False

    根据给定的绝对和相对容差确定两个值是否被认为是接近的。rel_tol 是相对容差 —— 它是 ab 之间允许的最大差值,相对于 ab 的较大绝对值。

    例如,要设置5%的容差,请传递 rel_tol=0.05 。默认容差为 1e-09,确保两个值在大约9位十进制数字内相同。 rel_tol 必须大于零。abs_tol 是最小绝对容差 —— 对于接近零的比较很有用。 abs_tol 必须至少为零。

  • math.isfinite(x)

    如果 x 既不是无穷大也不是NaN,则返回 True ,否则返回 False

  • math.isinf(x)

    如果 x 是正或负无穷大,则返回 True ,否则返回 False

  • math.isnan(x)

    如果 x 是 NaN(不是数字),则返回 True ,否则返回 False

  • math.ldexp(x, i)

    返回 x * (2**i) 。 这基本上是函数 frexp()的反函数。

  • math.modf(x)

    返回 x 的小数和整数部分。两个结果都带有 x 的符号并且是浮点数。

  • math.remainder(x, y)

    返回 IEEE 754 风格的 x 相对于 y 的余数。对于有限 x 和有限非零 y ,这是差异 x - n*y ,其中 n 是与商 x /y 的精确值最接近的整数。如果 x / y 恰好位于两个连续整数之间,则最近的 * even* 整数用于 n 。 余数 r =remainder(x, y) 因此总是满足 abs(r) <= 0.5 * abs(y)

    特殊情况遵循IEEE 754:特别是 remainder(x, math.inf) 对于任何有限 x 都是 x ,而 remainder(x, 0)remainder(math.inf, x) 引发 ValueError 适用于任何非NaN的 x 。如果余数运算的结果为零,则该零将具有与 x 相同的符号。

    在使用IEEE 754二进制浮点的平台上,此操作的结果始终可以完全表示:不会引入舍入错误。3.7 新版功能.

  • math.trunc(x)

    返回 Realx 截断为 Integral(通常是整数)。 委托给x.__trunc__()

幂函数与对数函数

  • math.exp(x)

    返回 ex 幂,其中 e = 2.718281… 是自然对数的基数。

    这通常比 math.e ** xpow(math.e, x) 更精确。

  • math.expm1(x)

    返回 ex 次幂,减1。这里 e 是自然对数的基数。

    对于小浮点数 xexp(x) - 1 中的减法可能导致 significant loss of precision

  • math.log(x[, base])

    使用一个参数,返回 x 的自然对数(底为 e )。

    使用两个参数,返回给定的 base 的对数 x ,计算为 log(x)/log(base)

  • math.log1p(x)

    返回 1+x (base e) 的自然对数。以对于接近零的 x 精确的方式计算结果。

  • math.log2(x)

    返回 x 以2为底的对数。这通常比 log(x, 2) 更准确。

  • math.log10(x)

    返回 x 底为10的对数。这通常比 log(x, 10) 更准确。

  • math.pow(x, y)

    将返回 xy 次幂。

    特别是, pow(1.0, x)pow(x, 0.0) 总是返回 1.0 ,即使 x 是零或NaN。

    如果 xy 都是有限的, x 是负数, y 不是整数那么 pow(x, y) 是未定义的,并且引发 ValueError

    与内置的 ** 运算符不同, math.pow()将其参数转换为 float类型。使用 ** 或内置的 pow() 函数来计算精确的整数幂。

  • math.sqrt(x)

    返回 x 的平方根。

三角函数

  • math.acos(x)

    以弧度为单位返回 x 的反余弦值。

  • math.asin(x)

    以弧度为单位返回 x 的反正弦值。

  • math.atan(x)

    以弧度为单位返回 x 的反正切值。

  • math.atan2(y, x)

    以弧度为单位返回 atan(y / x) 。结果是在 -pipi 之间。

    从原点到点 (x, y) 的平面矢量使该角度与正X轴成正比。

    atan2() 的点的两个输入的符号都是已知的,因此它可以计算角度的正确象限。

    例如, atan(1)atan2(1, 1) 都是 pi/4 ,但 atan2(-1, -1)-3*pi/4

  • math.cos(x)

    返回 x 弧度的余弦值。

  • math.hypot(x, y)

    返回欧几里德范数, sqrt(x*x + y*y) 。 这是从原点到点 (x, y) 的向量长度。

  • math.sin(x)

    返回 x 弧度的正弦值。

  • math.tan(x)

    返回 x 弧度的正切值。

角度转换

  • math.degrees(x)

    将角度 x 从弧度转换为度数。

  • math.radians(x)

    将角度 x 从度数转换为弧度。

双曲函数

双曲函数 是基于双曲线而非圆来对三角函数进行模拟。

  • math.acosh(x)

    返回 x 的反双曲余弦值。

  • math.asinh(x)

    返回 x 的反双曲正弦值。

  • math.atanh(x)

    返回 x 的反双曲正切值。

  • math.cosh(x)

    返回 x 的双曲余弦值。

  • math.sinh(x)

    返回 x 的双曲正弦值。

  • math.tanh(x)

    返回 x 的双曲正切值。

特殊函数

  • math.erf(x)

    返回 x 处的 error functionerf() 函数可用于计算传统的统计函数。

  • math.erfc(x)

    返回 x 处的互补误差函数。 互补错误函数 定义为 1.0 - erf(x)。 它用于 x 的大值,从其中减去一个会导致 有效位数损失

  • math.gamma(x)

    返回 x 处的 伽马函数 值。

  • math.lgamma(x)

    返回Gamma函数在 x 绝对值的自然对数。

常量

  • math.pi

    数学常数 π = 3.141592…,精确到可用精度。

  • math.e

    数学常数 e = 2.718281…,精确到可用精度。

  • math.tau

    数学常数 τ = 6.283185…,精确到可用精度。

    Tau 是一个圆周常数,等于 2π,圆的周长与半径之比。

  • math.inf

    浮点正无穷大。 (对于负无穷大,使用 -math.inf 。)相当于float('inf') 的输出。

  • math.nan

    浮点“非数字”(NaN)值。 相当于 float('nan') 的输出。

Math skill

1. average - 平均值

返回两个或多个值的平均值

Returns the average of two or more numbers.

Use sum() to sum all of the args provided, divide by len(args).

def average(*args):
    return sum(args, 0.0) / len(args)
Examples
average(*[1, 2, 3]) # 2.0
average(1, 2, 3) # 2.0
2. average_by - 函数映射后的平均值

返回一个列表中所有经过函数处理的元素的平均值

Returns the average of a list, after mapping each element to a value using the provided function.

Use map() to map each element to the value returned by fn.
Use sum() to sum all of the mapped values, divide by len(lst).

def average_by(lst, fn=lambda x: x):
    return sum(map(fn, lst), 0.0) / len(lst)
Examples
average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n']) # 5.0
3. clamp_number

将num限制在边界值a和b指定的范围内。

如果num在此范围内,则返回num。

否则,返回范围内最接近的数字。

Clamps num within the inclusive range specified by the boundary values a and b.

If num falls within the range, return num.
Otherwise, return the nearest number in the range.

def clamp_number(num,a,b):
    return max(min(num, max(a,b)),min(a,b))
Examples
clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1
4. digitize - 转数组

将一个数转换为数字数组。

Converts a number to an array of digits.

Use map() combined with int on the string representation of n and return a list from the result.

def digitize(n):
    return list(map(int, str(n)))
Examples
digitize(123) # [1, 2, 3]
5. factorial - 阶乘

计算数字的阶乘

Calculates the factorial of a number.

Use recursion.
If num is less than or equal to 1, return 1.
Otherwise, return the product of num and the factorial of num - 1.
Throws an exception if num is a negative or a floating point number.

def factorial(num):
    if not ((num >= 0) and (num % 1 == 0)):
      raise Exception(
        f"Number( {num} ) can't be floating point or negative ")
    return 1 if num == 0 else num * factorial(num - 1)
Examples
factorial(6) # 720
6. fibonacci - 斐波那契数列

生成斐波那契数列

Generates an array, containing the Fibonacci sequence, up until the nth term.

Starting with 0 and 1, use list.apoend() to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches n.
If n is less or equal to 0, return a list containing 0.

def fibonacci(n):
    if n <= 0:
      return [0]

    sequence = [0, 1]
    while len(sequence) <= n:
      next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
      sequence.append(next_value)

    return sequence
Examples
fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13]
7. gcd - 最大公约数

计算数字列表的最大公约数。

Calculates the greatest common divisor of a list of numbers.

Use reduce() and math.gcd over the given list.

from functools import reduce
import math

def gcd(numbers):
    return reduce(math.gcd, numbers)
Examples
gcd([8,36,28]) # 4
8. in_range - 判断范围

检查给定数字是否在给定范围内

Checks if the given number falls within the given range.

Use arithmetic comparison to check if the given number is in the specified range.
If the second parameter, end, is not specified, the range is considered to be from 0 to start.

def in_range(n, start, end = 0):
    if (start > end):
      end, start = start, end
    return start <= n <= end
Examples
in_range(3, 2, 5); # True
in_range(3, 4); # True
in_range(2, 3, 5); # False
in_range(3, 2); # False
9. is_divisible - 整除

检查第一个数值参数是否可被第二个数值参数整除。

Checks if the first numeric argument is divisible by the second one.

Use the modulo operator (%) to check if the remainder is equal to 0.

def is_divisible(dividend, divisor):
    return dividend % divisor == 0
Examples
is_divisible(6, 3) # True
10. is_even - 偶数

如果给定数字为偶数,则返回’true’,否则返回’false’。

Returns True if the given number is even, False otherwise.

Checks whether a number is odd or even using the modulo (%) operator.
Returns True if the number is even, False if the number is odd.

def is_even(num):
    return num % 2 == 0
Examples
is_even(3) # False
11. is_odd - 奇数

如果给定数字为偶数,则返回’true’,否则返回’false’。

Returns True if the given number is odd, False otherwise.

Checks whether a number is even or odd using the modulo (%) operator.
Returns True if the number is odd, False if the number is even.

def is_odd(num):
    return num % 2 != 0
Examples
is_odd(3) # True
12. 最小公倍数

返回两个或多个数字的最小公倍数。

Returns the least common multiple of two or more numbers.

Define a function, spread, that uses either list.extend() or list.append() on each element in a list to flatten it.
Use math.gcd() and lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple.

from functools import reduce
import math

def spread(arg):
    ret = []
    for i in arg:
      if isinstance(i, list):
        ret.extend(i)
      else:
        ret.append(i)
    return ret

def lcm(*args):
    numbers = []
    numbers.extend(spread(list(args)))

    def _lcm(x, y):
        return int(x * y / math.gcd(x, y))

    return reduce((lambda x, y: _lcm(x, y)), numbers)
Examples
lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60
13. max_by - 函数映射后的最大值

在使用所提供的函数将每个元素映射到每一个值后返回一个列表的最大值。

Returns the maximum value of a list, after mapping each element to a value using the provided function.

Use map() with fn to map each element to a value using the provided function, use max() to return the maximum value.

def max_by(lst, fn):
    return max(map(fn,lst))
Examples
max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 8
14. median - 中值

查找列表中元素的中值。

Finds the median of a list of numbers.

Sort the numbers of the list using list.sort() and find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even.

def median(list):
    list.sort()
    list_length = len(list)
    if list_length%2==0:
  	    return (list[int(list_length/2)-1] + list[int(list_length/2)])/2
    else:
        return list[int(list_length/2)]
Examples
median([1,2,3]) # 2
median([1,2,3,4]) # 2.5
15. min_by - 函数映射后的最小值

在使用所提供的函数将每个元素映射到每一个值后返回一个列表的最小值。

Returns the minimum value of a list, after mapping each element to a value using the provided function.

Use map() with fn to map each element to a value using the provided function, use min() to return the minimum value.

def min_by(lst, fn):
    return min(map(fn,lst))
Examples
min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 2
16. rads_to_degrees - 弧度转角度

将角度从弧度转换为角度。

Converts an angle from radians to degrees.

Use math.pi and the radian to degree formula to convert the angle from radians to degrees.

import math

def rads_to_degrees(rad):
    return (rad * 180.0) / math.pi
Examples
import math
rads_to_degrees(math.pi / 2) # 90.0
17. sum_by - 求和

使用提供的函数将每个元素映射到值后,返回列表的和。

Returns the sum of a list, after mapping each element to a value using the provided function.

Use map() with fn to map each element to a value using the provided function, use sum() to return the sum of the values.

def sum_by(lst, fn):
    return sum(map(fn,lst))
Examples
sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 20
  • 19
    点赞
  • 129
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值