Friday, January 11, 2019

Python Math module

The math module gives you access to hyperbolic, trigonometric, and logarithmic functions for real numbers. In addition, some mathematical constants are also defined in this module. Let's explore this module.


A. Numeric Functions

1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned.

2. floor() :- This function returns the greatest integral value smaller than the number. If number is already integer, same number is returned.

3. fabs() and abs() :- This function returns the absolute value of the number. The fabs() method takes a decimal (float) number as a parameter and returns its absolute value (which is always positive). We also have the global abs() function which works with integers.

4. factorial() :- This function returns the factorial of the number. An error message is displayed if number is not integral.

5. copysign(a, b) :- This function returns the number with the value of ‘a’ but with the sign of ‘b’. The returned value is float type.

6. gcd() :- This function is used to compute the greatest common divisor of 2 numbers mentioned in its arguments.

Now let's use these functions in programs and see the operations. See the code below:

import math

num = 5.6
x = -15
y = 9
val1 = -10
val2 = 5.5
num1 = 15
num2 = 5

# returning the ceil 
print ("The ceil of "+str(num)+"  is : ", end="") 
print (math.ceil(num)) 
  
# returning the floor  
print ("The floor of "+str(num)+"  is : ", end="") 
print (math.floor(num)) 

# returning the absolute value 
print ("The absolute value of "+str(x)+"  is : ", end="") 
print (math.fabs(x)) 
  
# returning the factorial  
print ("The factorial of "+str(y)+"  is : ", end="")
print (math.factorial(y))

# returning the copysigned value. 
print ("The copysigned value of "+str(val1)+ " and "+ str(val2) +"  is : ", end="") 
print (math.copysign(val1, val2)) 
  
# returning the gcd 
print ("The gcd of "+str(num1)+ " and "+ str(num2)+"  is : ", end="") 
print (math.gcd(num1,num2)) 

The output of this program is shown below:

The ceil of 5.6  is : 6
The floor of 5.6  is : 5
The absolute value of -15  is : 15.0
The factorial of 9  is : 362880
The copysigned value of -10 and 5.5  is : 10.0
The gcd of 15 and 5  is : 5

------------------
(program exited with code: 0)

Press any key to continue . . .

B. Power and logarithmic functions

1. exp(x) :- This function returns e raised to the power x, where e = 2.718281… is the base of natural logarithms.

2. expm1(x)
Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in exp(x) - 1 can result in a significant loss of precision; the expm1() function provides a way to compute this quantity to full precision

3. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentioned, the computed value is of natural log. With two arguments, return the logarithm of a to the given base, calculated as log(a)/log(b).

4. log2(a) :- This function computes value of log a with base 2. This value is more accurate than the value of the function discussed above.

5. log10(a) :- This function computes value of log a with base 10. This value is more accurate than the value of the function discussed above.

6. log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero

7. pow(x, y)
Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError.

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

8. sqrt(x)
Return the square root of x.

Now let's use these functions in programs and see the operations. See the code below:

import math

# returning the exp 
print ("The exp of 5 is : ", end="")
print (math.exp(5)) 
   
# returning the log of a,b 
print ("The log of 2,3 is : ", end="") 
print (math.log(2,3)) 

# returning the log2 

print ("The log2 of 32 is : ", end="")
print (math.log2(32)) 
   
# returning the log10 

print ("The log10 of 100000 is : ", end="")
print (math.log10(100000)) 

# returning the log1p 
print ("The log1p(0.0000025) is : ", end="")
print(math.log1p(0.0000025))

# returning the expm1 
print ("The expm1(1e-5) is : ", end="")
print(math.expm1(1e-5))

# returning the pow 
print ("The pow(144, 0.5) is : ", end="")
print(math.pow(144, 0.5))

# returning the sqrt 
print ("The sqrt(144) is : ", end="")
print(math.sqrt(144) )

The output of this program is shown below:

The exp of 5 is : 148.4131591025766
The log of 2,3 is : 0.6309297535714574
The log2 of 32 is : 5.0
The log10 of 100000 is : 5.0
The log1p(0.0000025) is : 2.4999968750052084e-06
The expm1(1e-5) is : 1.0000050000166667e-05
The pow(144, 0.5) is : 12.0
The sqrt(144) is : 12.0

------------------
(program exited with code: 0)

Press any key to continue . . .

C. Trigonometric and Angular Functions
The math module contains functions for calculating various trigonometric ratios for a given angle. We can calculate sin(x), cos(x), and tan(x) directly using this module. However, there is no direct formula to calculate cosec(x), sec(x), and cot(x), but their value is equal to the reciprocal of the value returned by sin(x), cos(x), and tan(x) respectively.

Instead of calculating the value of trigonometric functions at a certain angle, you can also do the inverse and calculate the angle at which they have a given value by using asin(x), acos(x), and atan(x). 

The functions (sin, cos, tan, etc.) need the angle in radians as an argument. We, on the other hand, are used to express the angle in degrees. To convert degrees to radians we multiply them by (Math.PI / 180). The return value is also a double.

1. math.acos(x)
Return the arc cosine of x, in radians.

2. math.asin(x)
Return the arc sine of x, in radians.

3. math.atan(x)
Return the arc tangent of x, in radians.

4. math.atan2(y, x)
Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4.

5. math.cos(x)
Return the cosine of x radians.

6. math.hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y).

7. math.sin(x)
Return the sine of x radians.

8. math.tan(x)
Return the tangent of x radians.

Angular conversion

1. math.degrees(x)
Convert angle x from radians to degrees.
2. math.radians(x)
Convert angle x from degrees to radians.

Hyperbolic functions

Hyperbolic functions are analogs of trigonometric functions that are based on a hyperbola instead of a circle. In trigonometry, the points (cos b, sin b) represent the points of a unit circle. In the case of hyperbolic functions, the points (cosh b, sinh b) represent the points that form the right half of an equilateral hyperbola. 

Just like the trigonometric functions, you can calculate the value of sinh(x), cosh(x), and tanh(x) directly. The rest of the values can be calculated using various relations among these three values. There are also other functions like asinh(x), acosh(x), and atanh(x), which can be used to calculate the inverse of the corresponding hyperbolic values. The following are the 

1. math.acosh(x)
Return the inverse hyperbolic cosine of x.

2. math.asinh(x)
Return the inverse hyperbolic sine of x.

3. math.atanh(x)
Return the inverse hyperbolic tangent of x.

4. math.cosh(x)
Return the hyperbolic cosine of x.

5. math.sinh(x)
Return the hyperbolic sine of x.

6. math.tanh(x)
Return the hyperbolic tangent of x.

Let's make a program and use the above discussed functions. See the code below:

import math

a = math.pi/6
x = math.pi/6
y = 3
z = 4
in_radians = math.pi/6
in_degrees = 30
   
# returning the value of sine of pi/6 
print ("The value of sine of pi/6 is : ", end="") 
print (math.sin(a)) 
   
# returning the value of cosine of pi/6 
print ("The value of cosine of pi/6 is : ", end="") 
print (math.cos(a)) 

   
# returning the value of tangent of pi/6 
print ("The value of tangent of pi/6 is : ", end="") 
print (math.tan(x)) 
   
# returning the value of hypotenuse of 3 and 4 
print ("The value of hypotenuse of 3 and 4 is : ", end="") 
print (math.hypot(y,z)) 

  
# returning the converted value from radians to degrees 
print ("The converted value from radians to degrees is : ", end="") 
print (math.degrees(in_radians)) 
   
# returning the converted value from degrees to radians 
print ("The converted value from degrees to radians is : ", end="") 
print (math.radians(in_degrees))


print ("The arc sine value is : ", end="")
math.asin(0.7071067811865476)

print ("The arc cosine value is : ", end="")
print(math.acos(0))

print ("The arc tangent value is : ", end="")
print(math.atan(0.5773502691896257))

# Hyperbolic functions

print ("The sinh value is : ", end="")
print(math.sinh(math.pi))

print ("The cosh value is : ", end="")
print(math.cosh(math.pi))

print ("The tanh value is : ", end="")
print(math.tanh(math.pi))

print ("The asinh value is : ", end="")
print(math.asinh(11.548739357257746))

print ("The acosh value is : ", end="")
print(math.acosh(11.591953275521519)) 

print ("The atanh value is : ", end="")
print(math.atanh(0.99627207622075))

The output is shown below:

The value of sine of pi/6 is : 0.49999999999999994
The value of cosine of pi/6 is : 0.8660254037844387
The value of tangent of pi/6 is : 0.5773502691896257
The value of hypotenuse of 3 and 4 is : 5.0
The converted value from radians to degrees is : 29.999999999999996
The converted value from degrees to radians is : 0.5235987755982988
The arc sine value is : The arc cosine value is : 1.5707963267948966
The arc tangent value is : 0.5235987755982988
The sinh value is : 11.548739357257746
The cosh value is : 11.591953275521519
The tanh value is : 0.99627207622075
The asinh value is : 3.141592653589793
The acosh value is : 3.141592653589793
The atanh value is : 3.141592653589798

------------------
(program exited with code: 0)

Press any key to continue . . .

D. Special functions

The math module defines some special function as shown below:

erf(x)
Return the error function at x. The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution.

erfc(x)
Return the complementary error function at x. The complementary error function is defined as 1.0 - erf(x). It is used for large values of x where a subtraction from one would cause a loss of significance.

gamma(x)
Return the Gamma function at x.

lgamma(x)
Return the natural logarithm of the absolute value of the Gamma function at x.

Let's make a program and use the above discussed functions. See the code below:

import math 
  
a = 4
  
# returning the gamma() of 4 
print ("The gamma() of 4 is : ", end="") 
print (math.gamma(a))

# returning the lgamma() of 4 
print ("The lgamma() of 4 is : ", end="") 
print (math.lgamma(a))

# returning the erf()of 4 
print ("The erf() of 4 is : ", end="") 
print (math.erf(a))

# returning the erfc() of 4 
print ("The erfc() of 4 is : ", end="") 
print (math.erfc(a))

The output is shown below:

The gamma() of 4 is : 6.0
The lgamma() of 4 is : 1.7917594692280554
The erf() of 4 is : 0.9999999845827421
The erfc() of 4 is : 1.541725790028002e-08
------------------
(program exited with code: 0)

Press any key to continue . . .

E. Constants

The math module defines some constants also which are as follows:

1. math.pi

Pie (π) is a well-known mathematical constant, which is defined as the ratio of the circumference to the diameter of a circle and its value is 3.141592653589793. 

2. math.e
Another well-known mathematical constant defined in the math module is e. It is called Euler's number and it is a base of the natural logarithm. Its value is 2.718281828459045.

3. math.tau
The mathematical constant τ = 6.283185…, to available precision. Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to its radius. 

4. math.inf
A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf').

5. math.isinf() :- This function is used to check whether the value is an infinity or not.

6. math.nan
A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan').

7. math.isnan() :- This function returns true if the number is “nan” else returns false.

Now let's print the value of these constants and use the discussed methods. See the code below:

import math

print("Pi: %f" % (math.pi))
print("e: %f" % (math.e))
print("τ: %f" % (math.tau))
# checking if number is nan 

if (math.isnan(math.nan)):
print ("The number is nan") 
else :
print ("The number is not nan") 
  
# checking if number is positive infinity 
if (math.isinf(math.inf)):
print ("The number is positive infinity") 
else :
print ("The number is not positive infinity") 

The output of this program is shown below:

Pi: 3.141593
e: 2.718282
τ: 6.283185
The number is nan
The number is positive infinity

------------------
(program exited with code: 0)

Press any key to continue . . .

Here I am ending today's discussion. Till we meet next keep practicing and learning Python as Python is easy to learn!

Share:

0 comments:

Post a Comment