In python numeric data types store numeric values. Number objects are created when a value is assigned to them.
num1 = 5 num2 = 10
Four different numerical types are supported in python:
- int (signed integers)
- long (long integers, they can also be represented in octal and hexadecimal)
- float (decimal/real values)
- complex (complex numbers)
Python includes following functions for numbers:
|abs(x)||It returns the absolute value of x|
|math.ceil(x)||It returns the ceiling of x: nearest larger integer. Ex: math.ceil(3.1) = 4|
|cmp(x, y)||It returns 1 if x > y, 0 if x == y, or -1 if x < y|
|exp(x)||It returns ex. In python 3 you have to use math.exp(1)|
|fabs(x)||It returns the absolute value of x in float|
|math.floor(x)||The floor of x: nearest smaller integer. Ex: math.floor(x)|
|math.log(x)||It returns the natural logarithm of x, where x> 0. You can define the base as math.log(x,base)|
|math.log10(x)||It returns the logarithm base-10 of x, where x> 0|
|max(x1, x2,…)||It returns the largest among passed arguments|
|min(x1, x2,…)||It returns the smallest of among passed arguments|
|math.modf(x)||It returns two tuple value consisting of (fractional, integer parts of x) and both parts have the same sign as x. The integer part is returned as a float.|
|pow(x, y)||It returns x**y.|
|round(x, n)||It returns rounded value of x, to n digits from the decimal point. Python rounds to greater integer for a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.|
|math.sqrt(x)||It returns the square root of x, where x > 0|
Random Number Functions
Python includes following functions that are widely used. You have to import random library to use these functions.
|choice(seq)||It returns a randomly selected item from the passed argument, that could be:sequence, tuple, or string,|
|random.randrange (start, last, step)||It returns a randomly selected value between start and stop, with step value as step. Ex: random.randrange(2,10,1), returns a random value from 2, 3, 4, 5, 6, 7, 8, 9, 10|
|random.random()||It returns a random float vaule x, such that 0 ≤ x < 1|
|random.seed(x)||In python random numbers are generated by performing some operation on a number and usually this number is a previously generated random number. So for the 1st time x is used to generate the random number. If you provide the same value of x, the same random numbers will be generated. Best is to use current time as x in seed.|
|random.shuffle(list)||It randomizes the items of a list in place. Returns None. Ex:x=[1,2,3,4],random.shuffle(x),x= [2, 1, 3, 4]|
|uniform(x, y)||It returns a random float value f, such that x ≤ f &t; y|
In python trigonometric functions are avaiabe in math ibrary.
math.acos(x), math.asin(x), math.atan(x), math.atan2(y, x), math.cos(x), math.hypot(x, y), math.sin(x), math.tan(x), math.degrees(x), math.radians(x).
In python pi and e are the two mathematical constants. They can be used as math.pi and math.e.