python math模块详解_math在python中是什么意思-程序员宅基地

技术标签: math模块  python库  

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
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Jarrodche/article/details/102537164

智能推荐

在ubuntu 8.04下安装Oracle 11g二-程序员宅基地

文章浏览阅读408次。 在ubuntu 8.04下安装Oracle 11g2008年05月22日 星期四 11:02oracle 11g 数据库虽然提供了linux x86的版本,但是支持的linux版本只有Red Hat,Novell and Solaris 这几个,debian 和 ubuntu 不在支持之列,所以在ubuntu下安装就相对麻烦一些,请照着下文的方法一步一步的安装,不

初一计算机知识点下册,初一英语下册语法知识点全汇总-程序员宅基地

文章浏览阅读166次。新东方在线中考网整理了《初一英语下册语法知识点全汇总》,供同学们参考。一. 情态动词can的用法can+动词原形,它不随主语的人称和数而变化。1. 含有can的肯定句:主语+can+谓语动词的原形+其他。2. 含有can的否定句:主语+can't+动词的原形+其他。3. 变一般疑问句时,把can提前:Can+主语+动词原形+其他? 肯定回答:Yes,主语+can。否定回答:No,主语+can't...._七年级下册计算机知识点

NX/UG二次开发—其他—UFUN函数调用Grip程序_uf调用grip-程序员宅基地

文章浏览阅读3k次。在平时开发中,可能会遇到UFUN函数没有的功能,比如创建PTP的加工程序(我目前没找到,哪位大神可以指点一下),可以使用Grip创建PTP,然后用UFUN函数UF_call_grip调用Grip程序。具体如下截图(左侧UFUN,右侧Grip程序):..._uf调用grip

Android RatingBar的基本使用和自定义样式,kotlin中文教程_ratingbar样式修改-程序员宅基地

文章浏览阅读156次。第一个:原生普通样式(随着主题不同,样式会变)第二个:原生普通样式-小icon第三个:自定义RatingBar 颜色第四个:自定义RatingBar DrawableRatingBar 各样式实现===============原生样式原生样式其实没什么好说的,使用系统提供的style 即可<RatingBarstyle="?android:attr/ratingBarStyleIndicator"android:layout_width=“wrap_cont.._ratingbar样式修改

OpenGL环境搭建:vs2017+glfw3.2.1+glad4.5_vs2017的opengl环境搭建(完整篇)-程序员宅基地

文章浏览阅读4.6k次,点赞6次,收藏11次。安装vs2017:参考vs2017下载和安装。安装cmake3.12.3:cmake是一个工程文件生成工具。用户可以使用预定义好的cmake脚本,根据自己的选择(像是Visual Studio, Code::Blocks, Eclipse)生成不同IDE的工程文件。可以从它官方网站的下载页上获取。这里我选择的是Win32安装程序,如图所示:然后就是运行安装程序进行安装就行。配置glfw3...._vs2017的opengl环境搭建(完整篇)

在linux-4.19.78中使用UBIFS_ubifs warning-程序员宅基地

文章浏览阅读976次。MLC NAND,UBIFS_ubifs warning

随便推点

计算机系统内存储器介绍,计算机系统的两种存储器形式介绍-程序员宅基地

文章浏览阅读2.2k次。计算机系统的两种存储器形式介绍时间:2016-1-6计算机系统的存储器一般应包括两个部分;一个是包含在计算机主机中的主存储器,简称内存,它直接和运算器,控制器及输入输出设备联系,容量小,但存取速度快,一般只存放那些急需要处理的数据或正在运行的程序;另一个是包含在外设中的外存储器,简称外存,它间接和运算器,控制器联系,存取速度虽然慢,但存储容量大,是用来存放大量暂时还不用的数据和程序,一旦要用时,就..._计算机存储器系统采用的是主辅结构,主存速度快、容量相对较小,用于 1 分 程序,外

西门子PLC的编程工具是什么?_西门子plc编程软件-程序员宅基地

文章浏览阅读5.6k次。1. STEP 7(Simatic Manager):STEP 7或者Simatic Manager是西门子PLC编程最常用的软件开发环境。4. STEP 7 MicroWin:STEP 7 MicroWn是一款专门针对微型PLC(S7-200系列PLC)的编程软件,是Simatic Manager的简化版。如果需要与PLC系统配合使用,则需要与PLC编程工具进行配合使用。除了上述软件之外,西门子还提供了一些配套软件和工具,如PLC模拟器、硬件调试工具等,以帮助PLC编程人员快速地进行调试和测试。_西门子plc编程软件

HashMap扩容_hashma扩容-程序员宅基地

文章浏览阅读36次。【代码】HashMap扩容。_hashma扩容

Eclipse maven项目中依赖包不全,如何重新加载?_maven资源加载不全,怎么重新加载-程序员宅基地

文章浏览阅读2.9k次。1mvn dependency:copy-dependencies2 项目右键 -> Maven -> Disable Maven Nature3 项目右键 -> Configure -> Convert to Maven Project_maven资源加载不全,怎么重新加载

mysql dml全称中文_MySQL语言分类——DML-程序员宅基地

文章浏览阅读527次。DMLDML的全称是Database management Language,数据库管理语言。主要包括以下操作:insert、delete、update、optimize。本篇对其逐一介绍INSERT数据库表插入数据的方式:1、insert的完整语法:(做项目的过程中将字段名全写上,这样比较容易看懂)单条记录插入语法:insert into table_name (column_name1,......_dml的全称是

【小工匠聊Modbus】04-调试工具-程序员宅基地

文章浏览阅读136次。可以参考: http://git.oschina.net/jrain-group/ 组织下的Java Modbus支持库Modbus-系列文章1、虚拟成对串口(1)下载虚拟串口软件VSPD(可在百度中搜索)image.png(2)打开软件,添加虚拟串口。在设备管理中,看到如下表示添加成功。..._最好用的 modebus调试工具

推荐文章

热门文章

相关标签