python math的基本用法

Constants of the math Module

>>> import math
>>> math.pi, math.tau
(3.141592653589793, 6.283185307179586)

>>> math.e
2.718281828459045
>>> math.inf
inf
>>> x = 1e10
>>> math.inf > x
True
>>> math.nan
nan

Arithmetic Functions

>>> math.factorial(5)
120

math.ceil() will return the smallest integer value that is greater than or equal to the given number

>>> math.ceil(-2.2), math.ceil(3.3)
(-2, 4)

floor() will return the closest integer value that is less than or equal to the given number.
This function behaves opposite to ceil().


>>> math.floor(4.4), math.floor(-2.2)
(4, -3)

Truncate Numbers With trunc()

When you get a number with a decimal point, you might want to keep only the integer part and eliminate the decimal part.

>>> math.trunc(22.12)
22

Find the Closeness of Numbers With Python isclose()

>>> math.isclose(4,5,rel_tol=0.1)
False
>>> math.isclose(4,5,abs_tol=1)
True

Power Functions

>>> math.pow(5, 2)
25.0
>>> math.pow(5, 2.4), pow(5, 2.4)
(47.59134846789696, 47.59134846789696)
import timeit
>>> timeit.timeit("10 ** 308")
0.7564038369999999
>>> timeit.timeit("pow(10, 308)")
0.8013294880000004
>>> timeit.timeit("math.pow(10, 308)", setup="import math")
0.1495649570000004

The reason behind the efficiency of math.pow() is the way that it’s implemented. It relies on the underlying C language

>>> math.exp, math.exp(2)
 (<function math.exp(x, /)>, 7.38905609893065)

Logarithmic Functions

>>> math.log(4) # base of e
1.3862943611198906
>>> math.log(math.pi, 2)  # base of pi (first argument)
1.651496129472319

other functions

  1. Convert Angle Values
  2. Calculate the Sum of Iterables
  3. Calculate the Square Root
  4. Calculate the Greatest Common Divisor

ref: https://realpython.com/python-math-module/#getting-to-know-the-python-math-module

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值