1. Python Mathematical Functions

1.1. Introduction 

The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using import math.
It gives access to the underlying C library functions. For example,

# Square root calculation
import math
math.sqrt(4)

The math module is only available when the data is treated as either an integer (a whole number) or a floating-point (a number with a decimal place). If data is stored as a string, even if it only contains numeric characters, Python is unable to perform calculations with it.

1.2. Functions in Python Math Module

Here is the list of functions and attributes defined in math module with a brief explanation of what they do. 

Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable) Returns an accurate floating point sum of values in the iterable
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number)
isinf(x) Returns True if x is a positive or negative infinity
isnan(x) Returns True if x is a NaN
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x - 1
log(x[, b]) Returns the logarithm of x to the base b (defaults to e)
log1p(x) Returns the natural logarithm of 1+x
log2(x) Returns the base-2 logarithm of x
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
acos(x) Returns the arc cosine of x
asin(x) Returns the arc sine of x
atan(x) Returns the arc tangent of x
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x
pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
e mathematical constant e (2.71828...)

2. Random module 

2.1. Introduction 

Python can generate random values. In reality, the values are not completely random as no computer can cope with that; instead it uses an incredibly complex algorithm that makes it virtually impossible to accurately predict its outcome so, in effect, it acts like a random function.

There are two types of random value that we will be looking at:

  • Random numbers within a specified range;
  • A random choice from a range of items that are input.

2.2. Functions in Python Random Module

Here is the list of functions defined in Random module with a brief explanation of what they do. 

Function Description
seed() Initialize the random number generator
getstate() Returns the current internal state of the random number generator
setstate() Restores the internal state of the random number generator
getrandbits() Returns a number representing the random bits
randrange() Returns a random number between the given range
randint() Returns a random number between the given range
choice() Returns a random element from the given sequence
choices() Returns a list with a random selection from the given sequence
shuffle() Takes a sequence and returns the sequence in a random order
sample() Returns a given sample of a sequence
random() Returns a random float number between 0 and 1
uniform() Returns a random float number between two given parameters
triangular() Returns a random float number between two given parameters, you can also set a mode parameter to specify the midpoint between the two other parameters
betavariate() Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)
expovariate() Returns a random float number based on the Exponential distribution (used in statistics)
gammavariate() Returns a random float number based on the Gamma distribution (used in statistics)
gauss() Returns a random float number based on the Gaussian distribution (used in probability theories)
lognormvariate() Returns a random float number based on a log-normal distribution (used in probability theories)
normalvariate() Returns a random float number based on the normal distribution (used in probability theories)
vonmisesvariate() Returns a random float number based on the von Mises distribution (used in directional statistics)
paretovariate() Returns a random float number based on the Pareto distribution (used in probability theories)
weibullvariate() Returns a random float number based on the Weibull distribution (used in statistics)
  • value between 0 and 1, 1 excluded : 
    • num = random.random()
  • integer between 0 and 3 inclusive : 
    • num = random.randint(0, 3)
  • value between the numbers 0 and 100 (inclusive) in steps of 5 : 
    • num = random.randrange(0,100,5)
  • Value from the options “red”, “black” or “green”  : 
    • colour = random.choice([“red”,“black”,“green”])

 3. Examples

EXO V.1. 

Ask the user to enter an integer that is over 500. Work out the square root of that number and display it to two decimal places.

import math
number = int(input("Enter a number over 500 :"))
square = math.sqrt(number)
print(round(square,2))

 EXO V.2. 

Ask the user to enter two numbers. Use whole number division to divide the first number by the second and also work out the remainder and display the answer in a user-friendly way (e.g. if they enter 7 and 2 display “7 divided by 2 is 3 with 1 remaining”).

num1 = int(input("Enter the first number :"))
num2 = int(input("Enter the second number :"))

ans1 = num1//num2
ans2 = num1%num2

print(f"{num1} divided by {num2} is {ans1} with {ans2} remaining")

 EXO V.3. 

Ask for the radius and the depth of a cylinder and work out the total volume (circle area*depth) rounded to three decimal places.

import math
radius = int(input("Enter the radius of the cercle:"))
depth = int(input("Enter the depth:"))

area = math.pi*(radius**2)
volume = area*depth

print("The volume is ", round(volume,3))

 EXO V.4. 

Display the following message:

1) Square
2) Triangle

Enter a number : 

If the user enters 1, then it should ask them for the length of one of its sides and display the area. If they select 2, it should ask for the base and height of the triangle and display the area. If they type in anything else, it should give them a suitable error message.

print("1) Square:")
print("2) Triangle")

selection = int(input("Enter a number:"))

if selection == 1:
    side = int(input("Enter the length of one side:"))
    area = side*side
    print("The area of your chosen shape is ",area)
elif selection ==2:
    base = int(input("Enter the length of the base:"))
    height = int(input("Enter the height of the triangle"))
    area = (base*height)/2
    print("The area of your chosen shape is ",area)
else:
    print("Incorrect option selected")

 EXO V.5. 

Randomly choose either true or false (“t” or “f”). Ask the user to make their choice. If their choice is the same as the randomly selected value, display the message “You win”, otherwise display “Bad luck”. At the end, tell the user if the computer selected true or false.

import random

answer = random.choice(["t", "f"])
guess = input("Enter (t)rue or (f)alse :")

if guess == answer :
    print("You win")
else:
    print("Bad luck")

if answer == "t":
    print("It was true")
else:
    print("It was false")

 EXO V.6. 

Randomly choose a number between 1 and 5. Ask the user to pick a number. If they guess correctly, display the message “Well done”, otherwise tell them if they are too high or too low and ask them to pick a second number. If they guess correctly on their second guess, display “Correct”, otherwise display “You lose”.

import random

num = random.randint(1,5)
guess = int(input("Enter a number :"))

if guess == num :
    print("Well done")
elif guess > num:
    print("Too high")
    guess = int(input("Guess again :"))
    if guess == num:
        print("Correct")
    else:
        print("You lose")
elif guess < num:
    print("Too low")
    guess = int(input("Guess again :"))
    if guess == num:
        print("Correct")
    else:
        print("You lose")

 EXO V.7. 

Randomly pick a whole number between 1 and 10. Ask the user to enter a number and keep entering numbers until they enter the number that was randomly picked.

import random
num = random.randint(1,10)

while 1:
    guess = int(input("Enter a number: "))
    if guess == num:
        break

 EXO V.8. 

Make a maths quiz that asks five questions by randomly generating two whole numbers to make the question (e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add a point to their score. At the end of the quiz, tell them how many they got correct out of five.

import random
score = 0
for i in range(1,6):
    num1 = random.randint(1,50)
    num2 = random.randint(1,50)
    sumof = num1 + num2
    print(f"{num1} + {num2} = ")
    answer = int(input("Your answer :"))
    if answer == sumof :
        score = score + 1

print(f"You scored {score} out of 5")

 

0 comment

There are no comments yet.

Log in to leave a reply

Related posts

Developing a Web Application with Django Part 1: Getting Started

1/12/2021

Developing a Web Application with Django Part 2: Templates

15/12/2021

Developing a Web Application with Django Part 3 : Models

7/1/2022