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

你可能感兴趣的:(python)