Jump Start With Python - Part 5 (Numbers)

This article is in continuation to my previous articles of the series Jump Start with Python. To read, please refer to these links:
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 and they are explained below:
  • int (Integers): They are 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 postfix (l/L).
  • float: Floating point numbers represent real numbers and are written with 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 two methods and 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 data type to be checked with respect to variable. It is a class name of 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 data type to a variable and internally convert numbers into an expression (if required) to a common data type for the ease of evaluation.

Python also supports explicit conversion of numeric data types, and this 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 and they are explained below:

    1.   Syntax: complex(var_name)

    In this method, var_name will be real part in complex number and its imaginary part will remain zero.



    2.   Syntax: complex(var_name1, var_name2)

    In this method, var_name1 will be real part in complex number and var_name2 will be its imaginary part.

Python Decimals

There are some limitations in float data type, which are actually limitations of computer hardware. It can be explained using the example below:

 
 
In the example above, 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. Due to which, most of the decimal fractions cannot be accurately stored, this may arise serious problems in research and banking sectors though this type of deviation is very small but, both 3.3 and 3.3000000000000003 will never be equal.
 
To overcome this problem, we have 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. 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 support for rational arithmetics.
Creating fractions using Fractions Module

There are many ways to create fractions using Fractions module and 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 "numbers.Integral" abstract base class in Python which give more additional operations that can be done using int with the help of certain methods and 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 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 and they are explained below:

    1.   length: To specify byte length for respective integer. Overflow Error is raised if length is not according to integer specified.
    2.   byteorder: To specify the byte order there are two schemes for byteorder, "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_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 To Bytes Method. It consists of three parameters and they are explained below:

    1. bytes: It is a byte object that is to be converted into integer.
    2. byteorder: To specify the byte order there are two schemes for byteorder, "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 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 case of infinities and Value Error in case of NaNs (Not-a-Number).



  • Is Integer Method: This method returns True if float instance is finite integer and False otherwise.

    Syntax: float_num.is_integer()



  • Hex Method: It is an instance method. This method returns hexadecimal string for floating point number specified as input. For finite numbers, the hexadecimal string is leaded by 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 hexadecimal string specified as input. Consists of one parameter and it is explained below:

    1.   hex_num: It is a hexadecimal string which will be converted to 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 absolute value of real number specified i.e. distance between 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 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 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 absolute method and returns absolute value of number specified as input, only difference is that it converts the number specified to 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 it is explained below,

    1.   num: Number specified as input.

    Syntax: math.floor(num)



  • Natural Logarithm Method: This method returns natural logarithm of number specified as input. It consists of one parameter and it is explained below,

    1.   num: Number specified as input.

    Syntax: math.log(num)



  • Base-10 Logarithm Method: This method returns base-10 logarithm of 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, ----- , numn.

    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, ----- , numn.

    Syntax: min(num1, num2, num3, ----)



  • Modf Method
    This method returns fractional and integer parts of number specified as input in the form of two item tuple. Both fractional and integer parts have same sign as that of number specified. Also, they are returned as floating point numbers. It consists of one parameter and it is explained below:
    1. num: Number specified as input.

    Syntax: math.modf(num)


  • Power Method
    This method returns exponentiation of numbers specified as input i.e. base and exponent. It consists of two parameters and they are explained below:
    1. b: It is base number specified as input.
    2. exp: It is exponent to which base number is to be raised.

    Syntax: math.pow(b, exp)


  • Round Method
    This method returns 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 square root of 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 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 number 1 with sign of number 2, both specified as input. It consists of two parameters and they are explained below:
    1. num1: Number 1 specified as input, it will get sign.
    2. num2: Number 2 specified as input, its sign will be copied.

    Syntax: math.copysign(num1, num2)


  • IsNaN Method

    This method checks if 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 it is explained below:

          1.   num: Number specified as input.

    Syntax: math.isnan(num)


  • Factorial Method

    This method returns factorial of a number specified as input. It raises Value Error if 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 additional module "random" to be imported. Some of 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 and they are explained below:
    1. start: It is starting point of the range and is included in the range.
    2. end: It is ending point of the range and is not included in the range.
    3. step: The steps to be added to number in order to decide random element.

    Syntax: random.randrange(start, end, step)


  • Random Method: This method returns a random floating point number "r", such that it is 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 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", such that it is greater than or equal to lower limit, and less than upper limit specified as input. It consists of two parameters and they are explained below:
    1. lower: It is lower limit of random float number.
    2. upper: It is upper limit of random float number.

    Syntax: random.upper(lower, upper)


  • Get State Method: This method returns a 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 it is explained below:
    1. k: It is number of random bits specified as input.

    Syntax: random.getrandbits(k)


  • Random Integer Method

    It is similar to Random Range Method. This method return a random integer "n", such that it is greater than or equal to lower limit and less than or equal to upper limit. It consists of two parameters and they are explained below:
    1. lower: It is lower limit specified.
    2. upper: It is upper limit specified.

    Syntax: random.randint(lower, upper)


  • Sample Method
    This method returns a random sample list of length specified as input, from sequence list/population list specified. There is no replacement of elements in this method. Value Error is raised if sample size is specified larger than population size. It consists of two parameters and they are explained below:
    1. population: It is sequence list specified as input.
    2. k: It is number of elements to be included in sample.

    Syntax: random.sample(population, k)


  • Triangular Method

    This method generates a random floating point number "r", such that it is greater than or equal to lower limit specified, and less than or equal to lower limit specified with respect to median number specified as input. It consists of three parameters and they are explained below:
    1. lower: It is lower limit specified.
    2. upper: It is upper limit specified.
    3. mode: It is median number specified.

    Syntax: random.traingular(lower, upper, mode)


  • Betavariate Method

    This method is based on beta distribution and returns random value between 0 and 1 based on alpha and beta values specified as input. It consists of two parameters and they are explained below:
    1. alpha: It is alpha value specified and must be greater than 0.
    2. beta: It is 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 if value of lambda is positive while a value greater than 0 and less than negative infinity if value of lambda is negative. Lambda should be greater than 0. It consists of one parameter and it is explained below:
    1. lambd: It is a lambda value specified as input. "lambda" keyword can't be taken as parameter as it is reserved keyword by Python.

    Syntax: random.expovariate(lambd)


  • Gammavariate Method

    It is based on 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 alpha value specified.
    2. beta: It is 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 and consists of two parameters and they are explained below:
    1. mu: It is mean specified as input.
    2. sigma: It is standard deviation specified as input.

    Syntax: random.normalvariate(mu, sigma)


  • Gauss Method

    It is similar to normal variate method but is faster as compared to it. It is based on Gaussian Distribution. Takes mean and standard deviation as input and gives a random value. It consists of two parameters and they are explained below:
    1. mu: It is mean specified as input.
    2. sigma: It is 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. In this method mean can have any value but standard deviation should be greater than 0. It consists of two parameters and they are explained below:
    1. mu: It is mean specified as input.
    2. sigma: It is standard deviation specified as input.

    Syntax: random.lognormvariate(mu, sigma)


  • Vonmises Variate Method

    This is based on a distribution which results in reduction to a uniform angle over the range 0 to 2*pi. It generates random value based on two parameters specified as input and they are explained below:
    1. mu: It is mean angle specified as input and is expressed in form of radians over range 0 and 2*pi.
    2. kappa: It is concentration parameter.

    Syntax: random.vonmisesvariate(mu, kappa)


  • Pareto Variate Method

    It is based on Pareto Distribution. It generates a random value based on alpha value specified as input. It consists of one parameter and it is explained below:
    1. alpha: It is 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 and they are explained below:
    1. alpha: It is scale parameter specified as input.
    2. beta: It is shape parameter specified as input.

    Syntax: random.weibullvariate(alpha, beta)


Trigonometric Functions

Python provides various functions involving trigonometric calculations. They require "math" module to perform their operations, and they are explained below:
  • Sine Method: This method returns sine value of number specified as input in radians. It returns value between -1 and 1. It consists of one parameter and it is explained below,
    1. num: It is number specified as input.

    Syntax: math.sin(num)


  • Cosine Method: This method returns cosine value of number specified as 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 number specified as input.

    Syntax: math.cos(num)


  • Tangent Method: This method returns tangent value of number specified as input in radians. It consists of one parameter and it is explained below,
    1. num: It is number specified as input.

    Syntax: math.tan(num)


  • Arc Sine Method: This method returns arc sine value of number specified as input in radians. It consists of one parameter and it is explained below,
    1. num: It is number specified as input. Value of num must be in range of -1 and 1.

    Syntax: math.asin(num)


  • Arc Cosine Method: This method returns arc cosine value of number specified as input in radians. It consists of one parameter and it is explained below,
    1. num: It is number specified as input. Value of num must be in range of -1 and 1.

    Syntax: math.acos(num)


  • Arc Tangent Method: This method returns arc tangent value of number specified as input in radians. It consists of one parameter and it is explained below,
    1. num: It is number specified as input.

    Syntax: math.atan(num)


  • Arc Tangent Double Method

    This method returns arc tangent for two numbers specified as input in radians. It consists of two methods and they are explained below:
    1. num1: It is number specified as input.
    2. num2: It is number specified as input.

    Syntax: math.atan2(num1, num2)


  • Euclidean Method
    This method returns euclidean norm value of numbers specified as input. It consists of two parameters and they are explained below:
    1. num1: It is number specified as input.
    2. num2: It is number specified as input.
    Note: Euclidean Norm: sqrt(x*x + y*y)

    Syntax: math.hypot(num1, num2)


  • Degrees Method
    This method converts radians value to degree angle value for number specified as input. It consists of one parameter and it is explained below:
    1. num: It is radian value specified as input.

    Syntax: math.degrees(num)


  • Radians Method
    This method converts degrees value to radians value for the number specified as input. It consists of one parameter and it is explained below:
    1. num: It is degree angle value specified as input.

    Syntax: math.radians(num)

Up Next
    Ebook Download
    View all
    Learn
    View all