Python Math
Python provides a rich set of mathematical functions and constants through the built-in math
module. This module is always available and offers access to mathematical functions defined by the C standard.
Importing the math
Module
To use mathematical functions, you need to import the math
module.
import math
Mathematical Constants
The math
module provides several constants:
math.pi
- The mathematical constant π (pi), approximately 3.14159.math.e
- The mathematical constant e, approximately 2.71828.
Example: Using Mathematical Constants
# Using mathematical constants
import math
print("Value of pi:", math.pi)
print("Value of e:", math.e)
Value of pi: 3.141592653589793
Value of e: 2.718281828459045
Basic Mathematical Functions
Example 1: Calculating Square Roots
Use math.sqrt()
to calculate the square root of a number.
# Calculating square roots
import math
number = 16
sqrt_number = math.sqrt(number)
print("Square root of", number, "is", sqrt_number)
Square root of 16 is 4.0
Example 2: Exponential Functions
Use math.exp()
to calculate the exponential of a number (ex).
# Exponential functions
import math
x = 2
exp_x = math.exp(x)
print("e raised to the power", x, "is", exp_x)
e raised to the power 2 is 7.38905609893065
Example 3: Logarithmic Functions
Use math.log()
for natural logarithms and math.log10()
for base-10 logarithms.
# Logarithmic functions
import math
number = 1000
natural_log = math.log(number)
log_base10 = math.log10(number)
print("Natural log of", number, "is", natural_log)
print("Log base 10 of", number, "is", log_base10)
Natural log of 1000 is 6.907755278982137
Log base 10 of 1000 is 3.0
Example 4: Power Functions
Use math.pow(x, y)
to calculate x raised to the power y.
# Power functions
import math
base = 5
exponent = 3
power_result = math.pow(base, exponent)
print(f"{base} raised to the power {exponent} is {power_result}")
5 raised to the power 3 is 125.0
Trigonometric Functions
The math
module provides trigonometric functions which operate in radians.
Example 5: Calculating Sine, Cosine, and Tangent
Calculate the sine, cosine, and tangent of an angle in degrees.
# Trigonometric functions
import math
angle_deg = 45
angle_rad = math.radians(angle_deg)
sine = math.sin(angle_rad)
cosine = math.cos(angle_rad)
tangent = math.tan(angle_rad)
print(f"Sine of {angle_deg} degrees: {sine}")
print(f"Cosine of {angle_deg} degrees: {cosine}")
print(f"Tangent of {angle_deg} degrees: {tangent}")
Sine of 45 degrees: 0.7071067811865475
Cosine of 45 degrees: 0.7071067811865476
Tangent of 45 degrees: 0.9999999999999999
Example 6: Inverse Trigonometric Functions
Calculate the arc sine, arc cosine, and arc tangent.
# Inverse trigonometric functions
import math
value = 0.5
arc_sin = math.degrees(math.asin(value))
arc_cos = math.degrees(math.acos(value))
arc_tan = math.degrees(math.atan(value))
print(f"Arc Sine of {value}: {arc_sin} degrees")
print(f"Arc Cosine of {value}: {arc_cos} degrees")
print(f"Arc Tangent of {value}: {arc_tan} degrees")
Arc Sine of 0.5: 30.0 degrees
Arc Cosine of 0.5: 60.0 degrees
Arc Tangent of 0.5: 26.56505117707799 degrees
Hyperbolic Functions
The math
module includes hyperbolic functions such as math.sinh()
, math.cosh()
, and math.tanh()
.
Example 7: Calculating Hyperbolic Functions
# Hyperbolic functions
import math
x = 1
sinh = math.sinh(x)
cosh = math.cosh(x)
tanh = math.tanh(x)
print(f"sinh({x}) = {sinh}")
print(f"cosh({x}) = {cosh}")
print(f"tanh({x}) = {tanh}")
sinh(1) = 1.1752011936438014
cosh(1) = 1.5430806348152437
tanh(1) = 0.7615941559557649
Special Functions
Example 8: Factorials
Use math.factorial()
to calculate the factorial of a non-negative integer.
# Calculating factorial
import math
n = 5
fact = math.factorial(n)
print(f"Factorial of {n} is {fact}")
Factorial of 5 is 120
Example 9: Greatest Common Divisor
Use math.gcd()
to find the greatest common divisor of two integers.
# Finding GCD
import math
a = 48
b = 18
gcd = math.gcd(a, b)
print(f"GCD of {a} and {b} is {gcd}")
GCD of 48 and 18 is 6
Rounding Functions
Example 10: Floor and Ceiling
Use math.floor()
and math.ceil()
to round numbers down or up.
# Floor and ceiling
import math
number = 3.7
floor_value = math.floor(number)
ceil_value = math.ceil(number)
print(f"Floor of {number} is {floor_value}")
print(f"Ceiling of {number} is {ceil_value}")
Floor of 3.7 is 3
Ceiling of 3.7 is 4
Example 11: Truncation
Use math.trunc()
to truncate a floating-point number to an integer.
# Truncation
import math
number = -3.7
truncated_value = math.trunc(number)
print(f"Truncated value of {number} is {truncated_value}")
Truncated value of -3.7 is -3
Other Mathematical Functions
Example 12: Modulus and Remainder
Use math.fmod()
to get the modulus of two numbers.
# Modulus
import math
a = 20
b = 3
modulus = math.fmod(a, b)
print(f"Modulus of {a} % {b} is {modulus}")
Modulus of 20 % 3 is 2.0
Example 13: Copying Sign
Use math.copysign()
to return a float with the magnitude of the first parameter and the sign of the second.
# Copying sign
import math
x = 10
y = -5
result = math.copysign(x, y)
print(f"Result of copysign({x}, {y}) is {result}")
Result of copysign(10, -5) is -10.0
Degrees and Radians Conversion
Example 14: Converting Degrees to Radians
Use math.radians()
to convert degrees to radians.
# Degrees to radians
import math
degrees = 180
radians = math.radians(degrees)
print(f"{degrees} degrees is {radians} radians")
180 degrees is 3.141592653589793 radians
Example 15: Converting Radians to Degrees
Use math.degrees()
to convert radians to degrees.
# Radians to degrees
import math
radians = math.pi
degrees = math.degrees(radians)
print(f"{radians} radians is {degrees} degrees")
3.141592653589793 radians is 180.0 degrees
Practical Applications
Example 16: Calculating Distance Between Two Points
Calculate the Euclidean distance between two points in 2D space.
# Calculating distance between two points
import math
point1 = (2, 3)
point2 = (5, 7)
distance = math.hypot(point2[0] - point1[0], point2[1] - point1[1])
print(f"Distance between points: {distance}")
Distance between points: 5.0
Example 17: Calculating Compound Interest
Use exponential functions to calculate compound interest.
# Calculating compound interest
import math
principal = 10000 # Initial amount
rate = 5 # Interest rate in percent
time = 10 # Number of years
amount = principal * math.pow((1 + rate / 100), time)
print(f"Future amount after {time} years: {amount}")
Future amount after 10 years: 16288.94626777442
Example 18: Simulating Projectile Motion
Calculate the horizontal and vertical components of a projectile.
# Projectile motion components
import math
velocity = 50 # Initial velocity in m/s
angle_deg = 30 # Launch angle in degrees
angle_rad = math.radians(angle_deg)
horizontal_velocity = velocity * math.cos(angle_rad)
vertical_velocity = velocity * math.sin(angle_rad)
print(f"Horizontal Velocity: {horizontal_velocity} m/s")
print(f"Vertical Velocity: {vertical_velocity} m/s")
Horizontal Velocity: 43.30127018922194 m/s
Vertical Velocity: 24.999999999999996 m/s
Example 19: Calculating Area of a Circle
Compute the area of a circle given its radius.
# Area of a circle
import math
radius = 7
area = math.pi * math.pow(radius, 2)
print(f"Area of the circle: {area}")
Area of the circle: 153.93804002589985
Example 20: Using math.isclose()
Compare floating-point numbers for approximate equality.
# Comparing floating-point numbers
import math
a = 0.1 + 0.2
b = 0.3
are_close = math.isclose(a, b)
print(f"Is {a} approximately equal to {b}? {are_close}")
Is 0.30000000000000004 approximately equal to 0.3? True
Explanation: The math
module provides a comprehensive set of mathematical functions and constants. By importing this module, you can perform advanced mathematical operations with ease. Understanding these functions enhances your ability to solve complex mathematical problems in Python.