0% found this document useful (0 votes)
0 views19 pages

Numbers In Python

The document provides an overview of Python's numeric data types, including integers, floats, and complex numbers, along with their properties and methods for conversion and arithmetic operations. It also discusses the math module for mathematical functions and the decimal module for precise decimal arithmetic. Additionally, it covers implicit and explicit type conversions, as well as various built-in methods for numerical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views19 pages

Numbers In Python

The document provides an overview of Python's numeric data types, including integers, floats, and complex numbers, along with their properties and methods for conversion and arithmetic operations. It also discusses the math module for mathematical functions and the decimal module for precise decimal arithmetic. Additionally, it covers implicit and explicit type conversions, as well as various built-in methods for numerical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Numbers

Python Numeric Data Types:

A number is an arithmetic entity that lets us measure something.


Python allows us to store the integer, floating, and complex numbers and also
lets us convert between them.
Python is dynamically-typed, hence there is no need to specify the type of data
for a variable.
So now let’s start with python number types.

• None- The None keyword indicates the absence of value.

Python int:

Python can hold signed integers.

For example:
a=5

Python int hold a value of any length, the only limitation being the amount of
memory available.

For example:
a = 123456890000001234565

We can use type function to check the type of the value we have entered,

type(a)
<class ‘int’>

Python isinstance() function:


The isinstance() method returns True or False based on whether the construct
belongs to that class.

isinstance(a, bool)
it results False, because a is of type int.

Python Exponential numbers:

We can create an exponential number using the letter ‘e’ between the
mantissa and the exponent.

a = 2e2 # It is equivalent to 2 * 10 ** 2
print(a)
print(type(a))
print()
b = 2 * 10 ** 2
print(type(b))

Remember that the exponential e here is used to create powered values with
the base 10. To raise a number to another’s base power, we use the **
operator.

Python float:

Python supports floating-point real values.


# Python float
a = 1.123445000002
print(a)
# A float value is only accurate up to 15 decimal places. After that, it rounds
the number off.
a = 1.2345890000000012347898
print(a)
#%%
# Division results in floating point number.
a=2
b=3
divide = a / b
print(divide)
#%%
# A complex number is a Python number type made of real and imaginary
parts. It is represented as a+bj .
# Python Complex Numbers
z = 2 + 3j
print(z)
print(type(z))
To denote the irrational part, however, you can’t use the letter ‘i’, like you
would do on paper.
# creating 2 + 7i results an error.

#%%
# providing coefficient for 'j' is mandatory to create complex number
z=3+j
print(z)
# It results an error.
#%%
# We can use 1 to create complex number with the imaginary part
z = 3 + 1j
print(z)
#%%
a = 2 + 2j
b = 1 + 1j
# We can perform arithmetic operations on complex numbers as well,
# Remember that j^2 = -1
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print((1j)**2)
#%%
# We can also use inplace assignment operator on complex number
a = 2 + 2j
a += 2 + 4j
print(a)
#%%
# Writing numbers in binary, octal, and hexadecimal in Python
# We can write a binary number using the prefix 0b or 0B
bn1 = 0b1011
print(bn1)
bn2 = 0B1011
print(bn2)
#%%
# We can convert the binary numbers in to an int using int function
print(int(0b1011))
#%%
# Octal Numbers in Python : Uses prefix 0o or 0O
oc1 = 0o1234
print(oc1)
oc2 = 0O1234
print(oc2)

#%%
# Octal number has the numbers from 0-7
oc3 = 0o12348
print(oc3)
#%%
# Hexadecimal Numbers in Python
# The hexadecimal number system has numbers 0-9 and then A-F.
# and the prefix as 0x or 0X.
hexa1 = 0x1234
print(hexa1)
hexa2 = 0x12A
print(hexa2)
#%%
print(0XA)
print(0XB)
#%%
Python Conversion Functions
Although most times Python does the conversion as needed, you can do it
explicitly if you want.

These functions allow us to convert one numeric type into another python
numeric data types.

# Python Conversion Functions


# int() in Python
num1 = 2.745678
print(num1)
num2 = int(num1)
print(num2)

#%%
# We can't convert complex to int
a = 2 + 2j
b = int(a)
c = 2j
d = int(c)
#%%

# We can convert floats, binary, octal and hexadecimal number to an int


print(int(0b1011))
print(int(0o1234))
print(int(0x1234))
#%%
print(float(12))
#print(float(2 + 7j)) # It results an error
print(float(0b1011))
print(float(0o1234))
print(float(0x1234))
#%%
# complex() in Python
print(complex(2, 3))
print(complex(2))
print(complex(8j))
print(complex(2 + 3.784j))
a=4
b=3
print(complex(a, b))
#%%
# bin() in Python
print(bin(10))
print(bin(200))
print(bin(255))
print(bin(256))
#%%
# We can' convert float and complex numbers to binary form.
print(bin(12.0))
print(bin(2 + 5j))
#%%
# oct() in Python
print(oct(9))
print(oct(255))
print(oct(200.78)) # It returns error
#%%

#%%
# hex() in Python
print(hex(255))
print(hex(234.9))
print(hex(0))
print(hex(1))
print(hex(9))
print(hex(10))
Number Type Conversion
Python allows the conversion of data from one type to another in two ways.
• Implicit type conversion

• Explicit type conversion

Implicit Type Conversion


In the case of two compatible data types, Python performs the type conversion
implicitly. Compatible data types are in general two numeric data types like int
and float. It will convert the smaller data type to larger one to prevent any data
loss. For eg.; int data will be converted to float.
But, if we try to perform some operations between a string and int types then it will
throw Type error.

Let us see this with an example.

x = 99
y = 1.111

#data in int and float


print(type(x))
print(type(y))

#addition
z = x+y

#type after addition


print(type(z))

Explicit Type Conversion


We can convert data in one type to another explicitly using int(), float(),
complex() etc; This is called typecasting.

#concatenating int and str types


i = 99
s = "apple"
print(s+str(i))

Math Module Methods to work with Numerical Data

Python has built-in methods to perform complex mathematical operations.


In order to use them, we need to import the math module using the import
math statement. We will see some most widely used math methods with
examples.

ceil() and floor()

These two methods are used to round a float number to the nearest integer.
As the name suggests, ceil() method is used to round the number UP to the
nearest integer value while floor() is used to round a number DOWN to the
nearest integer value.
import math as m

a = 1.4
print(m.ceil(a))
print(m.floor(a))

degrees() and radians()

In trigonometric calculations, we represent angles in both degrees as well as radian’s


form.

We use the degrees() method to convert the angle in radians to degrees.


Similarly, we use radians() method to convert the angle in degrees to radians.

In addition to the above methods, math module also provides some frequently used
constants like pi. Let us see this with an example below.

import math

pi = math.pi
print(pi)
#To find the degree equivalent of the radians
print("Degree value of pi is ::",math.degrees(pi))

#Radians for the degrees


print("Radian value of 90 degree is ::",math.radians(90))

sin() and cos()

We can find the trigonometric sin and cos values using built-in methods in the
python math module.
We can find the sin value of an angle in radians using the sin() method. Similarly, we
can find the cos value of the angle in radians using the cos() method.

#sin value of 90
radians_90=math.radians(90)
print("sin value of pi/2 is ::", math.sin(radians_90))

#cos value of 60
radians_60 = math.radians(60)
print("cos value of pi/2 is ::", math.cos(radians_60))

factorial()

We can find the factorial of any positive integer using the


<code>factorial()</code> method in the math module. This method will
return the factorial value, multiplication of all the numbers from the specified
number until 1. E.g., the factorial of 5 is 5*4*3*2*1. Let us see this with an
example.
import math

#factorial of 6 : 6*5*4*3*2*1
print("factorial of 6 is ::", math.factorial(6))

fabs() and trunc()


We can use the fabs() method in the math module to find a number’s absolute
value as a float. This method will remove the negative sign, if any, and return
only the absolute float value.

We can truncate a number to its nearest integer using the trunc() method. This
method will not return the negative sign, if any.
import math

#floating absolute value


print("floating absolute value::", math.fabs(-99.999))
print("floating absolute value of an integer::", math.fabs(-11))

#truncated integer value


print("truncated integer value::", math.trunc(-99.99))
As we can see the fabs() method is returning the floating absolute value of
both a float number as well as an integer. The trunc() method returns the
truncated integer value of the given number which includes the negative sign
as well.

pow() and log()


We can find the natural log value of a number using the log() method
in math module.
The pow() method accepts two arguments, x, and y, and returns the value of x
raised to power y. Let us see both the methods with an example.
import math

print("The value of 9^3 is ::", math.pow(9, 3))


print("The log value of 5::", math.log(5))

Checking Functions
In math module, there are methods to check whether a number is either finite
or infinite. We also have a method to check whether an argument is number or
not.

isfinite() and isinf()


We can check whether a number is finite or not using the isfinite() method.
This method will return True if the value is finite and false if it is infinite. In the
same way, we can check whether a number is infinite or not using
the isinf() method.
#checking whether a number is finite or not
print("Finite or not::",math.isfinite(-0.00006))
#checking whether a number is infinite or not
print("Infinite or not::",math.isinf(math.inf))

isnan()

We can also check whether the argument we pass is a number or not using
the isnan() method.This method will return true the passed argument is not a
number.
#checking whether it is a number or not
print("IS a number or not::", math.isnan(math.nan))

isclose()

We can find whether two numbers are close or not using


the isclose() method. We can even mention the absolute tolerance which will
compare the numbers near 0 and it is the minimum tolerance. We can pass the
relative tolerance which is the maximum difference allowed between two
numbers.
#compare the closeness of two values
print("with absolute tolerance difference::", math.isclose(1.5, 2.05,
abs_tol = 0.55))

print("with relative difference < difference::",


math.isclose(1.5,1.75,rel_tol=0.5))

Square root, GCD, Power, and Exponentials of a Number

In addition to the above methods, there are methods that are commonly used like

• sqrt(): For finding the square root,

• gcd(): For finding the greatest common divisor,

• pow(x,y): For finding number x raised to power y and

• exp(x): exponentials of number x


Let us see one simple example for all the above functions.

#finding sqrt
print("The square root of 25 is ::", math.sqrt(25))
print("The square root of 10 is ::", math.sqrt(10))

#Greatest Common Divisor


print("The greatest common divisor is ::", math.gcd(6,12))

#exponential value
print("The value os e(x) is::", math.exp(-2))
#Number raised to power
print("The value of 9^3 is ::", math.pow(9, 3))

Other Python Number Methods


In addition to the above methods, there are few methods in Python for performing
some number-related operations. Let us see each with a small example.

bit_length()

This method is used to find the number of bits to represent a number in binary
format excluding the sign and leading zeros.

i=-99
print("bit length::", i.bit_length())

#checking by printing the binary version


bin(i)

to_bytes()

This method will return an array of bytes to represent an integer.

(24).to_bytes(3, byteorder='big')

The above output shows the array of bytes to represent the integer value 24.
The byteorder argument determines the byte order used to represent the integer. In
case the byteorder is “big”, the most significant byte is at the beginning of the byte
array. In case the byteorder is “little”, the most significant byte is at the end of the
byte array. The integer is represented using length bytes. If the integer cannot be
represented within that length then we will get Overflow error.

is_integer()

We can check whether the given number is an integer or not using


the is_integer() method. It will return a boolean value.

f=0.25

f.is_integer()

as_integer_ratio()

We can represent the floating number as an integer number ratio. In case of not a
perfect fraction ,then the nearest possible ratio will be returned.

f=0.25
f.as_integer_ratio()

Python Decimal Module


Python stores a decimal value internally as a base 2 binary fractions. For e.g 1/3 in
base 10 can be stored as 0.3, 0.33, or 0.3333. But we can add as many digits in the
end as possible to get to the near possible approximation.

Due to the limitations of the floating-point arithmetic some decimal numbers cannot
be represented exactly in base 2 binary fractions.
To prevent some data loss while performing mathematical operations, especially in
numbers with decimal digits, Python provides a separate module, ‘Decimal.’

Creating a Decimal Number

With the help of the decimal module we can actually set the precision of the number
to be displayed up to 28 digits. Based on the requirements we can actually specify
the amount of precision while representing the decimal numbers.

• Using decimal() constructor: We need to import the decimal module to


perform the following operations.

• Passing a tuple inside the decimal() constructor: Tuple will have three-
part. The first part will be 0 for positive and 1 for negative. The second
part will be the Integer component.
We can even set flags like ROUND_CEILING,ROUND_FLOOR,ROUND_UP,ROUND_DOWN and traps to
raise a Python exception during conditions like Division by Zero.By default certain
conditions like the division by zero are set to true only.

import decimal
from decimal import *

print(Decimal(0.01))
print(Decimal('0.05'))
print(Decimal((1, (9,9,9,9), -2)))

Decimal Methods

getcontext()

We can set the precision using the getcontext() method and even set the flags to
mention whether we need to round the digits up or Down.

print(Decimal(3) / Decimal(77))
We can limit the number of digits in the above output by setting the precision using
the getcontext().

getcontext().prec = 2
getcontext().rounding = decimal.ROUND_UP

print(Decimal(3) / Decimal(77))

Mathematical Operations

In addition to this, we have the flexibility of using all the mathematical functions
like sqrt,log , etc; available in the decimal module as well.

Note: It is very important to clear_flags() which we have already set in order to


adjust our precision differently for different requirements.

import decimal
from decimal import Decimal, getcontext
getcontext().clear_flags()
print(Decimal(2).sqrt())

Python Fraction Module


Python provides a separate module for handling the rational numbers called Fraction
Module.

A fraction can be formed from a decimal , float, integers ,another rational number or
a string.Let us see each one with a small example. We have to import the fractions
module first.

from fractions import Fraction

Let us see examples for each of the above.

from fractions import Fraction


#From two integers
Fraction(25, -100)
#From another fraction
Fraction(' -3/7 ')
#from a decimal
from decimal import Decimal
Fraction(Decimal('9.9'))
#from a decimal without quotes
from decimal import Decimal
Fraction(9.1)
#Empty Fraction
Fraction()

Fraction Module Methods

limit_denominator()

Some fractions are lengthy, and we can use the limit_denominator() method to limit
the number of digits in the denominator. Let us see this with an example.

As fractions have two parts, namely a numerator and a denominator, there are
methods to access both.

from fractions import Fraction


import math
#Fraction(math.pi).limit_denominator(100)
f=Fraction(math.pi).limit_denominator(100)
print("The fraction created is::",f)
print("Numerator::",f.numerator)

from_float()

We can create fractions from a floating number using the method.

Fraction.from_float(0.25)

Output
Fraction(1, 4)

ceil() and floor()

We can use the ceil() and floor() methods of the math module to find the nearest
integer above or below the fraction value.

import math
math.ceil(Fraction(300, 124))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy