Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Numbers (Number)

Python Numbers (Number)

The Python Number data type is used to store numeric values.

Data types are not allowed to be changed. This means that if you change the value of a Number data type, memory space will be reallocated.

In the following example, Number objects are created when variables are assigned:


var1 = 1
var2 = 10

You can also use the del statement to delete some references to Number objects.

The syntax of the del statement is:


del var1[,var2[,var3[....,varN]]]]

You can delete single or multiple objects by using the del statement, for example:


del var
del var_a, var_b

Python supports four different numeric types:

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

Python Number Type Conversion


int(x [,base ])         将x转换为一个整数  
long(x [,base ])        将x转换为一个长整数  
float(x )               将x转换到一个浮点数  
complex(real [,imag ])  创建一个复数  
str(x )                 将对象 x 转换为字符串  
repr(x )                将对象 x 转换为表达式字符串  
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象  
tuple(s )               将序列 s 转换为一个元组  
list(s )                将序列 s 转换为一个列表  
chr(x )                 将一个整数转换为一个字符  
unichr(x )              将一个整数转换为Unicode字符  
ord(x )                 将一个字符转换为它的整数值  
hex(x )                 将一个整数转换为一个十六进制字符串  
oct(x )                 将一个整数转换为一个八进制字符串  

The Python math module and cmath module

The functions commonly used for mathematical operations in Python are basically all in the math module and the cmath module.

The Python math module provides many mathematical functions for floating point numbers.

The Python cmath module contains some functions for complex number operations.

The functions in the cmath module are basically the same as those in the math module. The difference is that the cmath module operates on complex numbers, while the math module operates on numbers for mathematical computation.

To use math or cmath functions, you must first import them:

import math

View the contents of the math package:

>>> import math
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>>

The specific applications of each function will be introduced below.

View cmath to see the contents of the package

>>> import cmath
>>> dir(cmath)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>>

Example

>>> import cmath
>>> cmath.sqrt(-1)
1j
>>> cmath.sqrt(9)
(3+0j)
>>> cmath.sin(1)
(0.8414709848078965+0j)
>>> cmath.log10(100)
(2+0j)
>>>

Python Mathematical Functions

function Return value ( description )
abs(x) Return the absolute value of a number, e.g. abs(-10) returns 10
ceil(x) Return the ceiling of a number, e.g. math.ceil(4.1) returns 5
cmp(x, y) If x < x < y returns -1, x == y returns 0, x > y returns 1
exp(x) Return e raised to the power x (ex), e.g. math.exp(1) returns 2.718281828459045
fabs(x) Return the absolute value of a number as a float, e.g. math.fabs(-10) returns 10.0
floor(x) Return the floor of a number, e.g. math.floor(4.9) returns 4
log(x) e.g. math.log(math.e) returns 1.0 and math.log(100,10) returns 2.0
log10(x) Return the base-10 logarithm of x, e.g. math.log10(100) returns 2.0
max(x1, x2,...) Return the maximum of the given arguments; the argument can be a sequence.
min(x1, x2,...) Return the minimum of the given arguments; the argument can be a sequence.
modf(x) Return the integer and fractional parts of x; both have the same sign as x, and the integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n]) Returns the rounded value of the floating point number x. If n is given, it represents the number of digits after the decimal point to round to.
sqrt(x) Returns the square root of the number x

Python Random Number Functions

Random numbers are used in mathematics, games, security and other fields, and are often embedded into algorithms to improve efficiency and program security.

Python includes the following common random number functions:

function Description
choice(seq) Randomly pick an element from a sequence, e.g. random.choice(range(10)) picks a random integer from 0 to 9.
randrange ([start,] stop [,step]) Get a random number from a collection in a specified range increasing by a specified base; the base defaults to 1
random() Randomly generate the next real number in the range [0,1).
seed([x]) Change the seed of the random number generator. If you do not understand how it works, you need not set the seed yourself; Python will choose it for you.
shuffle(lst) Randomly shuffle all elements of a sequence
uniform(x, y) Randomly generate the next real number in the range [x,y].

Python Trigonometric Functions

Python includes the following trigonometric functions:

function Description
acos(x) Returns the arc cosine of x in radians.
asin(x) Returns the arc sine of x in radians.
atan(x) Returns the arc tangent of x in radians.
atan2(y, x) Returns the arc tangent of the given X and Y coordinate values.
cos(x) Returns the cosine of x radians.
hypot(x, y) Returns the Euclidean norm sqrt(xx + yy).
sin(x) Returns the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Convert radians to degrees, e.g. degrees(math.pi/2) returns 90.0
radians(x) Convert degrees to radians

Python Mathematical Constants

Constant Description
pi The mathematical constant pi (the ratio of a circle's circumference to its diameter, usually denoted by pi)
e The mathematical constant e, that is, the natural constant (Euler's number).