math — Mathematical functions

文章目录

  • math — Mathematical functions
    • 数论与表示函数
    • 幂函数与对数函数
    • 三角函数
    • 角度转换
    • 双曲函数
    • 特殊函数
    • 常量
    • Math skill
      • 1. average - 平均值
      • 2. average_by - 函数映射后的平均值
      • 3. clamp_number
      • 4. digitize - 转数组
      • 5. factorial - 阶乘
      • 6. fibonacci - 斐波那契数列
      • 7. gcd - 最大公约数
      • 8. in_range - 判断范围
      • 9. is_divisible - 整除
      • 10. is_even - 偶数
      • 11. is_odd - 奇数
      • 12. 最小公倍数
      • 13. max_by - 函数映射后的最大值
      • 14. median - 中值
      • 15. min_by - 函数映射后的最小值
      • 16. rads_to_degrees - 弧度转角度
      • 17. sum_by - 求和

数论与表示函数

  • 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 function 。erf() 函数可用于计算传统的统计函数。

  • 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 mathdef 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, endreturn 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 mathdef spread(arg):ret = []for i in arg:if isinstance(i, list):ret.extend(i)else:ret.append(i)return retdef 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)])/2else: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 mathdef 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

python math模块详解相关推荐

  1. python re正则_正则表达式+Python re模块详解

    正则表达式(Regluar Expressions)又称规则表达式,在代码中常简写为REs,regexes或regexp(regex patterns).它本质上是一个小巧的.高度专用的编程语言. 通 ...

  2. python time模块详解

    python time模块详解 转自:http://blog.csdn.net/kiki113/article/details/4033017 python 的内嵌time模板翻译及说明    一.简 ...

  3. Python—requests模块详解

    Python-requests模块详解 来源(博客园@小L小 ):Python-requests模块详解

  4. python cx_oracle模块详解_cx_Oracle模块详解

    1.安装cx_Oracle模块 1-1.环境准备: 1-1-1.oracle client最小安装 instantclient-sqlplus-linux.x64-11.2.0.4.0 instant ...

  5. Python shutil 模块详解

    Python shutil 模块详解 1.模块介绍 2.copytree 示例 3.move 示例 1.模块介绍 import shutil# copy data from file-like obj ...

  6. Python timeit 模块详解(准确测量小段代码的执行时间)

    timeit 模块详解 -- 准确测量小段代码的执行时间 timeit 模块提供了测量 Python 小段代码执行时间的方法.它既可以在命令行界面直接使用,也可以通过导入模块进行调用.该模块灵活地避开 ...

  7. Python Tkinter模块详解(后续持续补充)

    声明:该文章是个人学习中写的,目的是总结及当作工具参考,有一定的借鉴成分,后续若有新发现则补充 目录 Tkinter简介 创建组件基本语法 Tkinter组件汇总 Variable 类 常见参数详解 ...

  8. 【Python】模块详解/如何安装模块的方法

    什么是模块 一.模块.包 ①模块 Python 模块(Module) 实质上就是一个python集成文件.它是用来组织代码的,包含了 Python 对象定义和Python语句,意思就是把python代 ...

  9. python pexpect模块详解_python pexpect原理详解及使用说明

    pexpect是python中用于实现SSH,FTP,telnet等命令进行自动化交互,从而无需人工干预实现自动化运维的一个第三方扩展模块.理论的描述过于抽象,这里首先设想一下,如果让您设计一个实现自 ...

  10. python six模块详解_对python中的six.moves模块的下载函数urlretrieve详解

    实验环境:windows 7,anaconda 3(python 3.5),tensorflow(gpu/cpu) 函数介绍:所用函数为six.moves下的urllib中的函数,调用如下urllib ...

最新文章

  1. ”图书馆助手“典型用户和用户场景
  2. asp.net学习之Repeater控件
  3. 在ubuntu上使用SSH客户端
  4. 网站架构相关PPT、文章整理(更新于2009-7-15)
  5. 计算机word基础知识菜单,Word试卷模板_电脑基础知识_IT/计算机_资料
  6. Qt工作笔记-Qt奇淫技巧把ToolBar改成标题栏
  7. vb不能插入png图片_收藏备用!!VBA操作图片【插入导出删除】
  8. Apache OpenNLP
  9. 简述python_python 入门简述
  10. js 图表处理之Echar
  11. 怎么用 Photoshop 把图片变清晰?
  12. windows10定时关机如何设置
  13. bitcoin P2P协议分析
  14. 2016最新前端学习计划
  15. 京东订单拉取接入流程
  16. 我的DirectShow著作
  17. 9. Data Manipulation with dplyr in R
  18. Nginx 指定域名(或子域名)和网站绑定
  19. tftp服务器的配置
  20. 马云的 18 个合伙创办人现在各自情况怎样?

热门文章

  1. STM32F030 定时器
  2. 词根词缀学单词/优秀词典推荐
  3. 利用poi3.8中SXSSFWorkbook实现大数据量导出excel
  4. Servlet JSP 面试题
  5. 神经网络求解二阶常微分方程(代码)
  6. DSP6678入门必看
  7. HashMap底层原理与扩容机制
  8. Android 编辑 mhtml,Html Editor下载-Html Editor(Html编辑器)下载v1.0 安卓版-西西软件下载...
  9. 28-地理空间数据云下载
  10. 最长回文子串(Longest Palindromic Substring)——三种时间复杂度的解法及LeetCode[5] - 最长回文子串动态规划