Python Programming - Numbers

Python Programming – Numbers

A number is an object in Python, and it is created when some value is assigned to it. The number data type is used to hold numerical data. Python language supports four different numeric data types as described below:

• int (signed integers): Alike C/C++/Java, Python supports integer numbers, which are whole numbers positive as well as negative having no decimal point.

• long (long integers): Similar to integers but with limitless size. In Python long integers are followed by a lowercase or uppercase L.

• float (floating point real values): Alike C/C++/Java, Python supports real numbers, called floats. These numbers are written with-a decimal point or sometimes in a scientific notation, with exponent e such as 5.9e7 i.e. 5.9xl07, where e represents the power of 10.

• complex (complex numbers) : Unlike C/C++/Java, Python supports complex data type. It holds complex numbers of the form x+iy, where x and y are floating-point numbers and i is iota representing the square root of -1 (imaginary number). Complex numbers have two parts where x is known as the real part and y is called the imaginary, part as it is with iota.

Unlike C/C++/Java, in Python, the variable declaration is not mandatory. The programmer just assigns the value to a variable and that variable exists with the data type based on the value assigned. For example, Code: 5.1 (interactive mode) represents, an illustration of a number data type that how a variable holds a certain type of data and it exists.

Code: 5.1. Illustration of number data type.

>>>i = 123456789                                        # variable i is assigned an integer value
>>>i
123456789
>>> f = 9.8765432112345679564               # variable f is assigned a floating
#point value
>>>f
9.876543211234567
>>> c = 5+9j                                       # variable c is assigned a
#complex number value
>>>c
5+9j

The data type determination, reference deletion, and different types of numbers are already discussed in Chapter 2 under Section 2.8.1.

Number Type Conversion

Python has the in-built feature to convert the data types of an expression containing different data types into a common type for evaluation. However, in order to fulfill the requirements of an operator or a function argument, sometimes the programmer needs to convert a data type to another type forcibly. This can be achieved by type conversion functions as listed in Table 5.1.

Conversion function Role
int(x) converts x to a plain integer
long(x) converts x to a long integer
float(x) converts x to a floating-point number
complex(x) converts x to a complex number with real part x and imaginary part zero
complex(x, y) converts x and y to a complex number with real part x and imaginary part y. where x and y are numeric expressions

Python Mathematical Functions

Since we are working on numbers, Python language contains a rich set of built-in mathematical, and trigonometric, and random number functions, which operate on numbers input by the user. The mathematical functions are listed in Table 5.2. with a description of each of them. The programming example, representing the use of mathematical functions is given in Code: 5.2. The programmer needs to import the math namespace for executing mathematical functions.

Mathematical function

Computes/Returns

abs(x) The absolute value of x, which is a positive value
fabs(x) The absolute value of x
sqrt(x) The square root of x, where x>0
pow(x, y) The value of xy
ceil(x) The smallest integer not less than x
floor(x) The largest integer not greater than x
round(x, fn]) x rounded to n digits from the decimal point.
exp(x) The exponent of x, i.e., ex
log(x) The natural logarithm of x, where x>0
Logl0(x) The base-10 logarithm of x, where x>0
cmp(x, y) 0 if x=y, -1 if x<y, and 1 if x>y, (compares the values of x and y)
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as afloat
max(xl, x2, …) The largest value among its parameters
min(xl, x2, …) The smallest value among its parameters

Code: 5.2. Programming illustration of Python mathematical functions.

# This program represents the use of Python mathematical functions

import math
x=-10.5
y=abs(x)
print(‘abs(x)={0}\format(y))

x=9.5
y=math.fabs(x)
print(‘fabs(x)= {0} ‘.format(y))

x=256
y=math.sqrt(x)
print(‘sqrt(x)= {0} ‘.format(y))

x=2
y=16
z=math.pow(x, y)
print(‘pow({0}, {l})={2}’.format(x,y,z))

x=4.31
y=math.ceil(x)
print(‘ceil(x)= {0} ‘.format(y))

x=4.31
y=math.floor(x)
print(‘floor(x)= {0}format(y))

x=10.5628468
y=round(x, 3)
print(’round({0}, 3)={l}’.format(x, y))

x=2
y=math.exp(x)
print(‘exp(x)={0}’.format(y))

x=20
y=math.log(x)
print(‘log(x)= {0} ’.format(y))

x=20
y=math.loglO(x)
print(‘log 10(x)={0}’. format(y))

x=10
y=20
z=cmp(x,y)
print(‘cmp({0}, {l})={2}’.format(x, y, z))

x=12.4354683
y=math.modf(x)
print(‘modf(x)= {0} ’.format(y))

y=max(-10, 23,54,21,0)
print(‘max(-10, 23, 54, 21, 0)={0}’.format(y))

y=min(-10, 23, 54, 21, 0)
print(‘min(-10, 23, 54,21, 0)={0}’.format(y))

Output:
abs(x)=10.5
fabs(x)=9.5
sqrt(x)=16.0
pow(2, 16)=65536.0
ceil(x)=5
floor(x)=4
round(l0.5628468, 3)=10.563
exp(x)=7.38905609893065
log(x)=2.995732273553991
log10(x)=l.3010299956639813
cmp(10, 20)= -1
modf(x)=(0.435468300000000l4,12.0)
max(-10,23, 54, 21, 0)=54
min(-10, 23, 54,21, 0)=-10

Note:

Mathematical functions abs( ), round( ), and cmp( ) do not require to import math namespace.

Also Read: How to find the smallest number in an array java

Python Trigonometric Functions

Python language provides a set of trigonometric functions listed in Table 5.2. with the description of each. The programming code to characterize the use of trigonometric functions is given in Code: 5.3.

Trigonometric function

Returns

sin(x) Sine of x in radians
cos(x) Cosine of x in radians
tan(x) Tangent of x in radians
asin(x) Arc sine of x in radians
acos(x) Arc cosine of x in radians
atan(x) Arc tangent of x in radians
atan2(y, x) Atan(y/x) in radians
degrees(x) Converts an angle x from radians to degrees
radians(x) Converts an angle x from degrees to radians
hypot(x, y) Computes the Euclidean distance, i.e., sqrt(x*x+y*y)

Code: 5.3. Programming illustration of Python trigonometric functions.

# This program illustrates the use of trigonometric functions

import math

x=30
y=math.radians(x)
print(‘radians( {0} )= {1} ‘.format(x, y))

x=1.57
y=math.degrees(x)
print(‘degrees( {0} )= {1} ‘.format(x, y))

x=0.5235987755982988
y=math.sin(x)
print(‘sin({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.cos(x)
print(‘cos({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.tan(x)
print(‘tan({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.sin(x)
print(‘sin({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.acos(x)
print(‘acos( {0} )= {1}fomat(x, y))

x=0.5235987755982988
y=math.atan(x)
print(‘atan( {0})={ 1} ‘.format(x, y))
x=3
y=4
z=math.atan2(y, x)
print(‘atan2({0}, {l})={2}’.format(x, y, z))

x=3
y=4
z=math.hypot(x, y)
print(‘hypot({0}, {l})={2}’.format(x, y, z))

Output:
radians(30)=0.5235987755982988
degrees(1.57)=89.95437383553924
sin(0.5235987755982988)=0.49999999999999994
cos(0.5235987755982988)=0.8660254037844387
tan(0.5235987755982988)=0.5773502691896257
asin(0.5235987755982988)=0.5510695830994463
acos(0.5235987755982988)=l.0197267436954502
atan(0.5235987755982988)=0.48234790710102493
atan2(3,4)=0.9272952180016122
hypot(3, 4)=5.0

Python Random Number Functions

Random numbers are very useful in numerous computer science problems such as simulators, games, security, privacy, testing applications, etc. Python language provides a set of random number functions to handle various computer science problems as described above. The list of random number functions is given in Table 5.4. The programmer needs to import a random module before calling any of the random number functions. The programming example, representing the use of random number functions is given in Code 5.4.

Random number function

Returns

Random ( ) A random number r such that, 0 < r < 1
uniform(x, y) The random float r such that x < r < y
seed(x) It sets the starting integer value used in generating random numbers. This function is called before calling any other random number function.
choice(seq) A random item from a string, list, or tuple
shuffle(list) Randomizes the items in a list.
randfange(start, stop, step) A randomly selected item from a specified range.

Code: 5.4 Programming illustration of Python random number functions.

# This program illustrates the use of trigonometric functions

import random

r1 =random.random( )
print(“randomnumber l={0}”.format(rl))

r2=random.random( )
print(“random number 2={0} “.format(r2))

r1 =random.uniform( 10, 20)
print(“imiform random number l={0}”.format(r1))

r1=random.uniform(10,20)
print(“uniform random munber 2={0}”.format(r1))

random.seed(15)
r1 =random.random( )
print(“random number with seed 15={0}”.format(r1))

list=[70,20, 30,40, 50]
r1=random.choice(list)
print(“uniform random number l={0}”.format(r1))

str=’Hello Python’
r1=random.choice(str)
print(“uniform random number from string={0}”.format(r1))

list=[70, 20, 30,40, 50]
r1 =random. shuffle(list)
print(“shuffled list={0} “.format(list))

rl=random.randrange(10, 100, 3)
print(“random number from a range={0} “,format(rl))

rl=Thndom.randrange(10, 100, 4)
print(“random number from a range={0}”.format(rl))

Output:
random number 1=0.1113694067277533
random number 2=0.2822991673774605
uniform random number 1=18.907430735664263
uniform random number 2=10.620373343283184
random number with seed 15=0.965242141552123
uniform random number 1=70
uniform random number from string=t
shuffled list=[40, 30, 50,20, 70]
random number from a range=13
random number from a range=94

Python Mathematical Constants

Unlike, C/C++/Java, Python language provides built-in mathematical constants pi and e, which exhibit fixed values while performing mathematical computations. A program to illustrate mathematical constants is given in Code 5.5. Note that, the programmer requires to import a math module for fetching the values of pi and e.

Code: 5.5 Programming illustration of Python mathematical constants.

# Representation of mathematical constants pi and e

import math

print(‘pi= {0} ‘.format(math.pi))
print(‘e={0}’.format(math.e))

Output
pi=3.141592653589793
e=2.718281828459045

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *