Python Math Library and it’s Examples

0
1026

Introduction To Python Math Library

For a mathematical calculation in Python, In other words, you can use the built-in mathematics operators, such as addition(+), subtraction(-), multiplication(*), division(/). This operator is basic, and it is limited for calculation. So, more advanced math operations in a python, such as logarithmic, exponential, trigonometric function. All methods of these functions are used for integer or real type objects, not for complex numbers.

About Python math Module

The python math module is to deal with mathematical operations. It comes with already packages with standard function (operator). Most of the math Library is wrappers around ‘C’ platform’s mathematical functions. Therefore, it’s underlying functions are written in CPython.

Install math package:- you don’t have to install it separately. Already inbuilt in Python. just import like this, import math

Install math package

you don’t have to install it separately. Already inbuilt in Python math Library. just import like this, import math

Why math Library instead of NumPy?

NumPy vs math Use NumPy if you are doing scientific computations with arrays, matrices, or large datasets or 3D dimension datasets. NumPy is a third party package towards scientific computing. It means you have to install it. Mostly used are scientific computing and its data science field. It is best optimized for vector and array operations. The NumPy is high.

It is faster for such operations than say just using a list. For more details https://numpy.org/.Use math if you are doing simple computations with only scalars data, trigonometric computation not list, or arrays.math is a standard library.

It provides a basic mathematical function as well as advanced and constants. When working with scalar values, math Library can be faster than their NumPy counterparts. Because the NumPy functions convert into arrays

cmath vs math

The math module supplies mathematical functions on floating-point numbers, while the cmath module supplies equivalent functions on complex numbers.

A complex number is a combination of imaginary and real number.

formulated as a+bi,Where,

a = is a real number

bi = is an imaginary number

Real Number

A real number is a value of a continuous quantity that can represent a distance along a line. In other words, you can think of any number. Number of normal use, such as 1, 4.56, -7.8, 9/4Positive or negative, large or small, whole numbers or decimal numbers are all Real Numbers.

Imaginary number

An Imaginary number, When squared, gives a negative result.Imaginary numbers are shown as i

Arithmetic Function

They describe the arithmetic properties of numbers and are widely used in the field of number theory. The natural theory is a branch of pure mathematics, which is the study of natural numbers. Which deals with positive whole numbers or integers

Ceil()

This function returns the smallest integral value greater than or equal to the given number. If the given number is an integer, the same number is returned. If the number is a positive or negative decimal, then the function will return the next integer value greater than the given value.

import math
a = 9.8
b = math.ceil(a)
print("the ceil of 9.8 is:",b)

(the floor of 9.8 is :’, 9.0)

floor()

This function returns the greatest integral value smaller than the number. If the given number is an integer, the same number is returned.

a = 9.8
b = math.floor(a)
print("the floor of 9.8 is:",b)

(‘the floor of 9.8 is:’,9.0)


Widget not in any sidebars

Factorial()

This function returns the factorial of the number.

math.factorial(5)
out:-120
math.factorial(4.7)

ValueError                                Traceback (most recent call last)
<ipython-input-8-de4b77638d6b> in <module>()
----> 1 math.factorial(4.7)

ValueError: factorial() only accepts integral values

math.factorial(-8)

ValueError                                Traceback (most recent call last)
<ipython-input-9-a613a6ffd2a3> in <module>()
----> 1 math.factorial(-8)

ValueError: factorial() not defined for negative values

trunc()

It is the elimination part after the decimal point. It means when you get a number with a decimal point, you might want to keep only the integer part and eliminate the decimal part. Removing the decimal value is a type of rounding. The negative number always rounds off zero or positive

math.trunc(34.78)
output: 34
math.trunc(67)
output:67
math.trunc(-9.7)
output:-9

isclose()

To determine whether two numbers are close to each other.

Definition of Close: close means “near in time, space, effect”.

For Example, 1.47, 1.48, 1.478 measure closeness by two decimal points,1.47, 1.48

math.isclose(8,9)

False

math.isclose(8.8999,9)

True

Compare two numbers using the tolerances:

1. Relative tolerance:

or rel_tol, is the maximum difference for being considered “close”.The default value is 1e-092.

2: Absolute tolerance:

or abs_tol, is the maximum difference for being considered “close”.The default value is 0.0


Widget not in any sidebars

Logarithmic Function

The logarithmic function can be considered the inverse of exponential functions.Denoted by

Here b is the base of the logarithm, which can be any number.

Natural log

The logarithm having base e.

With the exponential function, natural log uses the constant e. It’s generally used to calculate values such as the rate of population growth. 


math.exp(32)

78962960182680.69

math.exp(-97)

7.47197233734299e-43

math.exp(5.6)

270.42640742615254

math.exp("y")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-4fce065a7e97> in <module>()
----> 1 math.exp("y")

TypeError: a float is required

log2() and log10()

The math module also provides two separate log functions that calculate the log values base 2 and 10.


math.log(math.pi,2)
o/p:-1.651496129472319

math.log(10,2)
o/p:- 3.3219280948873626

log10()

math.log10(math.pi)

0.4971498726941338

math.log10(6)

0.7781512503836436

math.log10(10)
1.0

Power Function

The power function takes any number x as input, raises x to some power n, and returns x power n. A power function is in the form of     f(x) = kx^n, where k = all real numbers and n = all real numbers. 

If n is greater than zero, then the function is proportional to the nth power of x.

  • pow(): Power functions have the following formula where the variable x is the base, the variable n is the power, and can be any constant.
f(x) = ax^n

Now, in python use math.pow() to get the power of numbers.

  • exp(): Is a natural exponent with exp(). Major difference is base being the variable, power becoming the variable.
f(x) = a^x

Here, 

a can be any constant and x which is the power value, becoming the variab

The specialization in the exponential function grows rapidly as the x value increases. If the base is greater than 1, then the function continuously increases in value x increases. The slope of these functions continuously increases as x increases.

f(x) = e^x
Power Function
math.pow(3,2)
9.0

math.pow(5,7)
78125.0

math.pow(5.56, 6)
29542.602396307444

math.pow(-9.54, 6)
753859.2155364405

Important Function:

  • Square Root:

math.sqrt(5)
2.23606797749979

math.sqrt(-8)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-41-9f6332b1593d> in <module>()
----> 1 math.sqrt(-8)

ValueError: math domain error

math.sqrt(5.6)
2.3664319132398464

The square root of a number is another number which produces the first number when it is multiplied by itself. In the python math module use math.sqrt() to find the square root of any positive real number. The real number is integer or decimal and the value returned is always a float value.

math.sqrt()

No square root of negative number.

  • Greatest Common Divisor(GCD):

print ("GCD of 75 and 30 is ",math.gcd(75, 30))

print ("GCD of 75 and 30 is ",math.gcd(75, 30))
​
GCD of 75 and 30 is 15

Also called the highest common divisor. GCD of two positive  integers a and b is the largest common to a and b.For example, the GCD 12 and 60 is 6. You can divide both 12 and 60 by 6 without any remainder.

The python module provides a function math.gcd()

  • Convert Angle Value

math.radians(23)
0.4014257279586958

math.degrees(23)
1317.8029288008934

math.radians(-9)
-0.15707963267948966

math.degrees(-18)
-1031.324031235482

Angles can be measured either by degrees or by radians. So sometimes you have to convert degrees to radians and vice versa.The python math module provides a function, you can use math.radians(). This function returns the radian value of degree input.

If you want to convert radians to degrees, then use math.degrees().

  • Trigonometric Value
  • SIN function-
SIN
import math
​
a = math.pi/5
​
a
0.6283185307179586
math.sin(a)
0.5877852522924731
math.sin(7)
0.6569865987187891
math.sin(-8)
-0.9893582466233818

COS function-

Cos
import math
​
a = math.pi/8
​
a
0.39269908169872414
math.cos(a)
0.9238795325112867
math.cos(-9)
-0.9111302618846769
math.cos(7)

TAN Function-

tan
import math
​
a = math.pi/5
​
a
0.6283185307179586
math.tan(a)
0.7265425280053609
math.tan(8)
-6.799711455220379
math.tan(-5)
3.380515006246586
hypotenuse
import math
​
a = 5
​
b = 7
math.hypot(a,b)
8.602325267042627
a = -9
​
c = -7
​
math.hypot(a,c)
11.40175425099138
Arc Cos
import math
​
a = math.pi/5
​
a
0.6283185307179586
math.acos(a)
0.8914064000439458
Pie
math.pi
3.141592653589793
r = 5
​
circumference = 2 * math.pi * r
​
circumference
31.41592653589793
r = 5
​
area = math.pi * r * r
​
area
78.53981633974483

Trigonometry deals with the study of triangles. It is the relationship between angles and sides of a triangle.The python math module provide useful functionality such as, 

  • sin value math.sin()
  • cosine value math.cos()
  • tan value math.tan()
  • arcsin value math.asin()
  • arc cosine value math.acos()
  • hypotenuse value math.hypot()

Constant Math Module:

Python math modules offer constants.It is part of a mathematical function.The most useful and famous mathematical constant are as follows,

  • Pie():

Which is defined as the ratio of the circumference to the diameter of a circle.= c / d

Here, 

c = circumference

d = diameter

its value is 3.141592653589793 or 22/7.(approximately: 3.14)Pie also denotes Pi. Pi is an irrational number, which means it can not be expressed as a simple fraction.

  • Euler’s Number:
Euler’s Number

math.e
2.718281828459045

It is a base of the natural logarithm.Euler’s number (e) is a constant is the base of the natural logarithm.It is an irrational number with finite decimal places. The value is 2.718281828459045. 

Form math module Math.e

  • Infinity: 
Infinity
positive_infnity = float('inf') 
print('Positive Infinity: ', positive_infnity) 
('Positive Infinity: ', inf)
negative_infnity = float('inf') 
print('Negative Infinity: ', positive_infnity) 
('Negative Infinity: ', inf)
test = float("inf")
test
inf

Simply it can’t be defined by a number.It is never-ending or boundaryless. It can be any direction it means positive or negative. Positive and Negative infinity in python are as follows:

  • Not a Number(NaN):
NaN
math.isnan
<function math.isnan>

It is not related to a mathematical function, it integrated the computer science field as a reference to value the not numeric.

Python math module: math.nan

LEAVE A REPLY

Please enter your comment!
Please enter your name here