Jump Start With Python - Part 5 (Numbers)

Introduction

 
This article a continuation of my previous articles in the series Jump Start with Python. To read more, please refer to these links:
A number is a mathematical object used to count, measure, label and manipulate. In Python, numbers are handled and manipulated using numeric data types. Python supports four different types of numeric data types that are explained below:
  • int (Integers): Positive or negative whole numbers with no decimal point.
  • long: They are also known as long integers of unlimited size. They are usually followed by a postfix (l/L).
  • float: Floating point numbers represent real numbers and are written with a decimal point dividing integer and fractional parts.
  • complex: Complex numbers are of the form (x + yJ), where x and y are floating point real values and J represents the square root of -1 i.e. an imaginary number.
We can detect/check the type of numeric data type using the two methods. They are explained below:
  • Type Method: It consists of one parameter:
     
    1.   var_name: It is the variable to be checked.
     
      Syntax: type(var_name)
     
     
     
  • Isinstance Method: It consists of two parameters:
     
    1.   var_name: It is a variable to be checked.
     
    2.   type: It is a number datatype to be checked with respect to a variable. It is a class name of the numeric data type.
     
    Syntax: isinstance(var_name, type)
     
     
Number System Prefix for Python
 
The examples quoted above are in decimal (base 10) number system. Python also handles other number systems which are binary (base 2), octal (base 8) and hexadecimal (base 16) respectively. These number systems are represented by placing a prefix before the number. Prefix table for respective number system as in the following,
  • Binary: Prefixed by - "0B" or "0b"
     
     
     
  • Octal: Prefixed by - "0O" or "0o"
     
     
  • Hexadecimal: Prefixed by - "0X" or "0x"
     
     
Numeric Data Type Conversion
 
Python automatically assigns a data type to a variable and internally convert numbers into an expression (if required) to a common data type for ease of evaluation.
 
Python also supports the explicit conversion of numeric data types in a process is known as Coercion. Syntax and examples for numeric data type conversion are explained below:
  • Conversion to Int (Integers)
     
    Syntax: int(var_name)
     
     
     
    NOTE: Python uses arbitrary long per default.
     
  • Conversion to Float
     
    Syntax: float(var_name)
     
     
  • Conversion to Complex: There are two different methods for type conversion to complex. They are explained below:
     
    1.   Syntax: complex(var_name)
     
    In this method, var_name will be the real part in a complex number and its imaginary part will remain zero.
     
     
    2.   Syntax: complex(var_name1, var_name2)
     
    In this method, var_name1 will be the real part in a complex number and var_name2 will be its imaginary part.
     
Python Decimals
 
There are some limitations in the float data type, which are actually limitations of computer hardware. It can be explained using the example below:
 
 
In the example above, the sum of x = 1.1 and y = 2.2 should be equal to 3.3 but rather it is equal to 3.3000000000000003. This is because floating-point numbers are implemented in computer hardware as binary fractions. Because of this, most of the decimal fractions cannot be accurately stored. This may bring serious problems in research and banking sectors, though this type of deviation is very small. However, both 3.3 and 3.3000000000000003 will never be equal.
 
To overcome this problem, we have the decimal module in Python which have precision as per user-specific scenario compared to floating-point numbers which have precision up to 15 decimal points. The Python decimal module is explained below:
 
 
Python Fractions 
  • Python provides operations for factorial numbers through its fractions module.
  • This module helps us to handle unusual results obtained by manipulating fractions using float data type. For example:
     
     
  • This module supports rational arithmetics.
Creating fractions using Fractions Module
 
There are many ways to create fractions using Fractions module. They are explained below:
 
 
Operations using Fractions Module: Fractions module support all basic operations and some of them are explained below,
  • Addition:
     
    Syntax: Fraction("num1") + Fraction("num2")
     
     
  • Subtraction:
     
    SyntaxFraction("num1") - Fraction("num2")
     
     
  • Multiplication:
     
    SyntaxFraction("num1") * Fraction("num2")
     
     
  • Division:
     
    SyntaxFraction("num1") / Fraction("num2")
     
     
  • Greater Than/ Greater Than Equal:
     
    Syntax: Fraction("num") > num/Fraction("num")Fraction("num") >= num/Fraction("num")
     
    Here, num is any number.
     
     
  • Less Than/ Less Than Equal:
     
    SyntaxFraction("num") < num/Fraction("num") | Fraction("num") <= num/Fraction("num")
     
    Here, num is any number.
     
     
Methods on Integer types
 
Integer implements the "numbers.Integral" abstract base class in Python which gives more additional operations that can be done using int with the help of certain methods. They are explained below:
  • Bit Length Method
     
    This method returns the number of bits required to represent an integer in binary. This method excludes sign convention and leading zeros also, it requires an integer to be converted to binary first.
     
    Syntax: var_name.bit_length()
     
     
  • To Bytes Method
     
    This method returns an array of bytes representing the integer specified as input. It consists of three parameters that are explained below:
     
    1.   length: To specify byte length for respective integer. Overflow Error is raised if the length is not according to integer specified.
     
    2.   byteorder: To specify the byte order there are two schemes for byte order, "big" and "little". If "big" is specified, then the most significant byte is
     
          at the start of an array while in the case of "little" it is at the end of the array.
     
    3.   signed: It determines whether two's complement is used to represent the integer or not. If it is "False" a negative integer is given and vice-
     
          versa. By default its "False".
     
    Syntax: int_num.to_bytes(length, byteorder, *,  signed)
     
     
  • From Bytes Method
     
    It is a class-level method. This method returns the integer represented by array of bytes specified as input. It is the inverse of the To Bytes Method. It consists of three parameters that are explained below:
     
    1. bytes: A byte object that is to be converted into an integer.
     
    2. byteorder: To specify the byte order, there are two schemes, "big" and "little". If "big" is specified then most significant byte is at starting of array while in case of "little" it is at the end of array.
     
    3. signed: It determines whether two's complement is used to represent the integer or not. If it is "False" a negative integer is given and vice-versa. By default its "False".
     
    Syntax: int.from_bytes(bytes, byteorder, *, signed)
     
Methods on Float types
 
Float implements "numbers.Float" abstract class in Python which give more additional operations that can be done using a float with the help of certain methods and they are explained below:
  • Integer Ratio Method: This method returns the pair of integers whose ratio is exactly equal to the original floating-point number along with a positive denominator.
     
    Syntax: float_num.as_integer_ratio()
     
    NOTE: It raises Overflow Error in the case of infinities and Value Error in the case of NaNs (Not-a-Number).
     
     
  • Is Integer Method: This method returns True if float instance is a finite integer and False otherwise.
     
    Syntax: float_num.is_integer()
     
     
  • Hex Method: It is an instance method. This method returns a hexadecimal string for a floating-point number specified as input. For finite numbers, the hexadecimal string is led by the prefix "0x" and postfixed by "p" and exponent.
     
    Syntax: float_num.hex()
     
     
  • From Hex Method: It is a class method. It returns the floating-point number represented by the hexadecimal string specified as input. It consists of one parameter and it is explained below:
     
    1.   hex_num: It is a hexadecimal string that will be converted to a floating-point number.
     
    Syntax: float.fromhex(hex_num)
     
     
Mathematical Functions & Constants: Python provides various functions to perform mathematical functions, they require additional module "math" to be imported. They are explained below:
  • PI (Constant)
     
    Pi is a mathematical constant and its value can be accessed directly.
     
    Syntax: math.pi
     
     
  • e (Constant): Exponential (e) is a mathematical constant and its value can be accessed directly.
     
    Syntax: math.e
     
     
  • Absolute: This method returns the absolute value of a real number specified i.e. distance between the real number and zero. It consists of one parameter and it is explained below:
     
    1.   num: Real number specified as input.
     
    Syntax: abs(num)
     
     
  • Ceiling Value: This method returns the ceiling value of the integer specified as input. It consists of one parameter and it is explained below:
     
    1.   num: Integer specified as input.
     
    Syntax: math.ceil(num)
     
     
  • Exponential Method: This method returns the exponential of the input number specified. It consists of one parameter and explained below:
     
    1.   num: Input number specified.
     
    Syntax: exp(num)
     
     
  • Absolute Method (fabs)
     
    It is similar to the absolute method and returns the absolute value of a number specified as input. The only difference is that it converts the number specified to a float first and they provide the absolute value. If it can't convert the number to float, then it will give an exception error. It consists of one parameter and it is explained below:
     
    1.   num: Number specified as input.
     
    Syntax: math.fabs(num)
     
     
  • Floor Method: This method returns the largest integer NOT greater than the number specified as input. It consists of one parameter and is explained below:
     
    1.   num: Number specified as input.
     
    Syntax: math.floor(num)
     
     
  • Natural Logarithm Method: This method returns the natural logarithm of the number specified as input. It consists of one parameter and is explained below:
     
    1.   num: Number specified as input.
     
    Syntax: math.log(num)
     
     
  • Base-10 Logarithm Method: This method returns base-10 logarithm of a number specified as input. It consists of one parameter and it is explained below:
     
    1.   num: Number specified as input.
     
    Syntax: math.log10(num)
     
     
     
  • Max Method: This method returns the largest argument/number i.e. number closest to infinity among arguments/numbers specified as input. It consists of n number of parameters ranging from num1, num2, num3, etc.
     
    Syntax: max(num1, num2, num3, -----)
     
     
  • Min Method: This method returns the smallest argument/number i.e. closest to negative infinity among arguments/numbers specified as input. It consists of n number of parameters ranging from num1, num2, num3, etc.
     
    Syntax: min(num1, num2, num3, ----)
     
     
  • Modf Method
     
    This method returns the fractional and integer parts of the number specified as the input in the form of a two-item tuple. Both fractional and integer parts have the same sign as that of the number specified. Also, they are returned as floating-point numbers. It consists of one parameter and is explained below:
     
    1. num: Number specified as input.
     
    Syntax: math.modf(num)
     
     
  • Power Method
     
    This method returns the exponentiation of numbers specified as input i.e. base and exponent. It consists of two parameters that are explained below:
     
    1. b: It is base number specified as input.
     
    2. exp: It is the exponent to which base number is to be raised.
     
    Syntax: math.pow(b, exp)
     
     
  • Round Method
     
    This method returns a number specified as input, rounded-off to n number of decimal points. It consists of two parameters and they are explained below:
     
    1. num: Number to be rounded off.
     
    2. n: Number of decimal points.
     
    Syntax: round(num, n)
     
     
  • Square Root Method
     
    This method returns the square root of the number specified as input. It consists of one parameter and is explained below:
     
    1. num: Number specified as input (num>0).
     
    Syntax: math.sqrt(num)
     
     
  • Truncation Method
     
    This method returns the real value of the number specified as input, truncated to an integral. It uses "__trunc__" method internally. It consists of one parameter and it is explained below:
     
    1. num: Number specified as input.
     
    Syntax: math.trunc(num)
     
     
  • Copy Sign Method
     
    This method returns the number 1 with the sign of number 2, both specified as inputs. It consists of two parameters and they are explained below:
     
    1. num1: Number 1 specified as input, it will get a sign.
     
    2. num2: Number 2 specified as input, its sign will be copied.
     
    Syntax: math.copysign(num1, num2)
     
     
  • IsNaN Method
     
    This method checks if the number specified as input is NaN (Not-a-Number) or not. If it is not it will return False, else it will return True. It consists of one parameter and is explained below:
     
          1.   num: Number specified as input.
     
    Syntax: math.isnan(num)
     
     
  • Factorial Method
     
    This method returns the factorial of a number specified as input. It raises a Value Error if the number is negative or not integral. It consists of one parameter and is explained below:
     
      1.   num: Number specified as input.
     
    Syntax: math.factorial(num)
     
     
Random Functions
Random numbers are used for simulation, testing, gaming, security, and privacy applications. Python provides various functions involving random numbers, they require an additional module, "random", to be imported. Some random functions are explained below:
  • Choice Method
     
    This method returns a random item from a list, tuple or string specified as input. It consists of one parameter and is explained below:
     
    1. seq: Input sequence specified.
     
    Syntax: random.choice(seq)
     
     
  • Random Range Method
     
    This method returns a randomly selected element from range specified as input. It consists of three parameters which are explained below:
     
    1. start: It is starting point of the range and is included in the range.
     
    2. end: It is the ending point of the range and is not included in the range.
     
    3. step: The steps to be added to the number in order to decide a random element.
     
    Syntax: random.randrange(start, end, step)
     
     
  • Random Method: This method returns a random floating-point number, "r", greater than 0 and less than 1.
     
    Syntax: random.random()
     
     
  • Seed Method
     
    This method is used to set the integer starting value used in generating random numbers. This function is generally called before calling any other random function. The method does not return any value, so it is called along with other random functions. It consists of one parameter and is explained below:
     
    1. s: This value is seed for the next random number.
     
    Syntax: random.seed(s)
     
     
  • Shuffle Method
     
    This method randomizes the position of elements present in a list or tuple specified as input. It consists of one parameter and is explained below:
     
    1. list: List or tuple specified as input.
     
    Syntax: random.shuffle(list)
     
     
  • Uniform Method
     
    This method returns a random floating-point number, "r", that it is greater than or equal to the lower limit, and less than the upper limit specified as input. It consists of two parameters which are explained below:
     
    1. lower: It is lower limit of a random float number.
     
    2. upper: It is upper limit of a random float number.
     
    Syntax: random.upper(lower, upper)
     
     
  • Get State Method: This method returns an object capturing the current internal state of random number generator.
     
    Syntax: random.getstate()
     
     
    Note: To define a custom state of random number generator "setstate()" method is used.
     
  • Random Bits Method
     
    This method returns a Python integer with specified random bits. It consists of one parameter and is explained below:
     
    1. k: It is the number of random bits specified as input.
     
    Syntax: random.getrandbits(k)
     
     
  • Random Integer Method
     
    It is similar to the Random Range Method. This method returns a random integer "n", such that it is greater than or equal to the lower limit and less than or equal to upper limit. It consists of two parameters and they are explained below:
     
    1. lower: It is the lower limit specified.
     
    2. upper: It is the upper limit specified.
     
    Syntax: random.randint(lower, upper)
     
     
  • Sample Method
     
    This method returns a random sample list of the length specified as input, from the sequence/population list specified. There are no elements replaced in this method. The Value Error is raised if the specified sample size is larger than the population size. It consists of two parameters which are explained below:
     
    1. population: It is a sequence list specified as input.
     
    2. k: It is number of elements to be included in the sample.
     
    Syntax: random.sample(population, k)
     
     
  • Triangular Method
     
    This method generates a random floating-point number, "r", that it is greater than or equal to the lower limit specified, and less than or equal to the lower limit specified with respect to the median number specified as input. It consists of three parameters which are explained below:
     
    1. lower: It is the lower limit specified.
     
    2. upper: It is the upper limit specified.
     
    3. mode: It is the median number specified.
     
    Syntax: random.traingular(lower, upper, mode)
     
     
  • Betavariate Method
     
    This method is based on beta distribution and returns a random value between 0 and 1 based on alpha and beta values specified as input. It consists of two parameters that are explained below:
     
    1. alpha: It is the alpha value specified and must be greater than 0.
     
    2. beta: It is the beta value specified and must be greater than 0.
     
    Syntax: random.betavariate(alpha, beta)
     
     
  • Expovariate Method
     
    It is based on exponential distribution. This method returns a random value greater than 0 and less than positive infinity as long as the value of lambda is positive, while a value greater than 0 and less than negative infinity if the value of lambda is negative. Lambda should be greater than 0. It consists of one parameter and it is explained below:
     
    1. lambd: This is a lambda value specified as an input. "lambda" keyword can't be taken as a parameter, as it is a reserved keyword in Python.
     
    Syntax: random.expovariate(lambd)
     
     
  • Gammavariate Method
     
    It is based on the gamma distribution. It generates a random floating point number based on alpha and beta values specified as input. It consists of two parameters and they are explained below:
     
    1. alpha: It is the alpha value specified.
     
    2. beta: It is the beta value specified.
     
    Syntax: random.gammavariate(alpha, beta)
     
     
  • Normal Variate Method
     
    It is based on Normal Distribution. It takes mean and standard deviation as inputs to generate a random value. It consists of two parameters which are explained below:
     
    1. mu: It is the mean specified as input.
     
    2. sigma: It is the standard deviation specified as input.
     
    Syntax: random.normalvariate(mu, sigma)
     
     
  • Gauss Method
     
    It is similar to the normal variate method but is faster compared to it. It is based on Gaussian Distribution. It takes mean and standard deviation as input and gives a random value. It consists of two parameters, explained below:
     
    1. mu: It is mean specified as input.
     
    2. sigma: It is the standard deviation specified as input.
     
    Syntax: random.gauss(mu, sigma)
     
     
  • Log-Normal Variate Method
     
    It is based on log-normal distribution. It takes mean and standard deviation as input to generate a random value using log-normal distribution. This method mean can have any value, but the standard deviation should be greater than 0. It consists of two parameters, explained below:
     
    1. mu: It is the mean specified as input.
     
    2. sigma: It is the standard deviation specified as input.
     
    Syntax: random.lognormvariate(mu, sigma)
     
     
  • Vonmises Variate Method
     
    This is based on a distribution that results in a reduction to a uniform angle over the range 0 to 2*pi. It generates a random value based on two parameters specified as input, explained below:
     
    1. mu: It is the mean angle specified as input and is expressed in the form of radians over the range 0 and 2*pi.
     
    2. kappa: It is a concentration parameter.
     
    Syntax: random.vonmisesvariate(mu, kappa)
     
     
  • Pareto Variate Method
     
    It is based on Pareto Distribution. It generates a random value based on the alpha value specified as input. It consists of one parameter which is explained below:
     
    1. alpha: It is a shape parameter specified as input.
     
    Syntax: random.paretovariate(alpha)
     
     
  • Weibull Variate Method
     
    It is based on Weibull Distribution. It generates a random value based on scale and shape parameters specified as input. It consists of two parameters, explained below:
     
    1. alpha: It is a scale parameter specified as input.
     
    2. beta: It is a shape parameter specified as input.
     
    Syntax: random.weibullvariate(alpha, beta)
     
     
Trigonometric Functions
 
Python provides various functions involving trigonometric calculations. They require "math" modules to perform their operations, and they are explained below:
  • Sine Method: This method returns the sine value of the number specified as an input in radians. It returns a value between -1 and 1. It consists of one parameter and it is explained below:
     
    1. num: It is the number specified as input.
     
    Syntax: math.sin(num)
     
     
  • Cosine Method: This method returns the cosine value of the number specified as an input in radians. It returns the value between -1 and 1 and consists of one parameter and it is explained below,
     
    1. num: It is the number specified as input.
     
    Syntax: math.cos(num)
     
     
  • Tangent Method: This method returns the tangent value of the number specified as an input in radians. It consists of one parameter and it is explained below:
     
    1. num: It is the number specified as input.
     
    Syntax: math.tan(num)
     
     
  • Arc Sine Method: This method returns the arc sine value of the number specified as an input in radians. It consists of one parameter which is explained below:
     
    1. num: It is the number specified as the input. The value of num must be in the range of -1 and 1.
     
    Syntax: math.asin(num)
     
     
  • Arc Cosine Method: This method returns the arc cosine value of the number specified as an input in radians. It consists of one parameter and is explained below:
     
    1. num: It is the number specified as input. The value of num must be within the range of -1 and 1.
     
    Syntax: math.acos(num)
     
     
  • Arc Tangent Method: This method returns the arc tangent value of the number specified as an input in radians. It consists of one parameter and is explained below:
     
    1. num: It is the number specified as input.
     
    Syntax: math.atan(num)
     
     
  • Arc Tangent Double Method
     
    This method returns arc tangent for two numbers specified as an input in radians. It consists of two methods which are explained below:
     
    1. num1: It is the number specified as input.
     
    2. num2: It is the number specified as input.
     
    Syntax: math.atan2(num1, num2)
     
     
  • Euclidean Method
     
    This method returns the euclidean norm value of numbers specified as input. It consists of two parameters which are explained below:
     
    1. num1: It is the number specified as input.
     
    2. num2: It is the number specified as input.
     
    Note: Euclidean Norm: sqrt(x*x + y*y)
     
    Syntax: math.hypot(num1, num2)
     
     
  • Degrees Method
     
    This method converts radian values to degree angle values for the number specified as input. It consists of one parameter and is explained below:
     
    1. num: It is a radian value specified as input.
     
    Syntax: math.degrees(num)
     
     
  • Radians Method
     
    This method converts the degrees value to a radians value for the number specified as input. It consists of one parameter and is explained below:
     
    1. num: It is the degree angle value specified as input.
     
    Syntax: math.radians(num)
     


Similar Articles