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

智能推荐

Docker 快速上手学习入门教程_docker菜鸟教程-程序员宅基地

文章浏览阅读2.5w次,点赞6次,收藏50次。官方解释是,docker 容器是机器上的沙盒进程,它与主机上的所有其他进程隔离。所以容器只是操作系统中被隔离开来的一个进程,所谓的容器化,其实也只是对操作系统进行欺骗的一种语法糖。_docker菜鸟教程

电脑技巧:Windows系统原版纯净软件必备的两个网站_msdn我告诉你-程序员宅基地

文章浏览阅读5.7k次,点赞3次,收藏14次。该如何避免的,今天小编给大家推荐两个下载Windows系统官方软件的资源网站,可以杜绝软件捆绑等行为。该站提供了丰富的Windows官方技术资源,比较重要的有MSDN技术资源文档库、官方工具和资源、应用程序、开发人员工具(Visual Studio 、SQLServer等等)、系统镜像、设计人员工具等。总的来说,这两个都是非常优秀的Windows系统镜像资源站,提供了丰富的Windows系统镜像资源,并且保证了资源的纯净和安全性,有需要的朋友可以去了解一下。这个非常实用的资源网站的创建者是国内的一个网友。_msdn我告诉你

vue2封装对话框el-dialog组件_<el-dialog 封装成组件 vue2-程序员宅基地

文章浏览阅读1.2k次。vue2封装对话框el-dialog组件_

MFC 文本框换行_c++ mfc同一框内输入二行怎么换行-程序员宅基地

文章浏览阅读4.7k次,点赞5次,收藏6次。MFC 文本框换行 标签: it mfc 文本框1.将Multiline属性设置为True2.换行是使用"\r\n" (宽字符串为L"\r\n")3.如果需要编辑并且按Enter键换行,还要将 Want Return 设置为 True4.如果需要垂直滚动条的话将Vertical Scroll属性设置为True,需要水平滚动条的话将Horizontal Scroll属性设_c++ mfc同一框内输入二行怎么换行

redis-desktop-manager无法连接redis-server的解决方法_redis-server doesn't support auth command or ismis-程序员宅基地

文章浏览阅读832次。检查Linux是否是否开启所需端口,默认为6379,若未打开,将其开启:以root用户执行iptables -I INPUT -p tcp --dport 6379 -j ACCEPT如果还是未能解决,修改redis.conf,修改主机地址:bind 192.168.85.**;然后使用该配置文件,重新启动Redis服务./redis-server redis.conf..._redis-server doesn't support auth command or ismisconfigured. try

实验四 数据选择器及其应用-程序员宅基地

文章浏览阅读4.9k次。济大数电实验报告_数据选择器及其应用

随便推点

灰色预测模型matlab_MATLAB实战|基于灰色预测河南省社会消费品零售总额预测-程序员宅基地

文章浏览阅读236次。1研究内容消费在生产中占据十分重要的地位,是生产的最终目的和动力,是保持省内经济稳定快速发展的核心要素。预测河南省社会消费品零售总额,是进行宏观经济调控和消费体制改变创新的基础,是河南省内人民对美好的全面和谐社会的追求的要求,保持河南省经济稳定和可持续发展具有重要意义。本文建立灰色预测模型,利用MATLAB软件,预测出2019年~2023年河南省社会消费品零售总额预测值分别为21881...._灰色预测模型用什么软件

log4qt-程序员宅基地

文章浏览阅读1.2k次。12.4-在Qt中使用Log4Qt输出Log文件,看这一篇就足够了一、为啥要使用第三方Log库,而不用平台自带的Log库二、Log4j系列库的功能介绍与基本概念三、Log4Qt库的基本介绍四、将Log4qt组装成为一个单独模块五、使用配置文件的方式配置Log4Qt六、使用代码的方式配置Log4Qt七、在Qt工程中引入Log4Qt库模块的方法八、获取示例中的源代码一、为啥要使用第三方Log库,而不用平台自带的Log库首先要说明的是,在平时开发和调试中开发平台自带的“打印输出”已经足够了。但_log4qt

100种思维模型之全局观思维模型-67_计算机中对于全局观的-程序员宅基地

文章浏览阅读786次。全局观思维模型,一个教我们由点到线,由线到面,再由面到体,不断的放大格局去思考问题的思维模型。_计算机中对于全局观的

线程间控制之CountDownLatch和CyclicBarrier使用介绍_countdownluach于cyclicbarrier的用法-程序员宅基地

文章浏览阅读330次。一、CountDownLatch介绍CountDownLatch采用减法计算;是一个同步辅助工具类和CyclicBarrier类功能类似,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。二、CountDownLatch俩种应用场景: 场景一:所有线程在等待开始信号(startSignal.await()),主流程发出开始信号通知,既执行startSignal.countDown()方法后;所有线程才开始执行;每个线程执行完发出做完信号,既执行do..._countdownluach于cyclicbarrier的用法

自动化监控系统Prometheus&Grafana_-自动化监控系统prometheus&grafana实战-程序员宅基地

文章浏览阅读508次。Prometheus 算是一个全能型选手,原生支持容器监控,当然监控传统应用也不是吃干饭的,所以就是容器和非容器他都支持,所有的监控系统都具备这个流程,_-自动化监控系统prometheus&grafana实战

React 组件封装之 Search 搜索_react search-程序员宅基地

文章浏览阅读4.7k次。输入关键字,可以通过键盘的搜索按钮完成搜索功能。_react search