×

Menu

Casting Different ways of writing integers Signed and unsigned integers in Python
Casting Different ways of writing floats Float precision Python Decimals Python Fractions
Complex numbers Type conversion
Number systems conversion Float to binary conversion
Size in memory Conclusion

AI_FOR_ALL

Python 101: DATA TYPES Ⅰ - NUMBERS

Published 18/3/217 min read
image

As discussed earlier Data types in Python are a way or categorizing or classifying data into different types. Data types tell us what kind of operations can be performed on a particular data There are seven different data types in Python, namely Numbers, Strings, Lists, Tuples, Sets, Booleans and Dictionaries. In this article we will be looking at Data type Numbers.

Numbers in Python are immutable (cannot be altered/changed after creation) and can be classified into three types:

Integers:

Integers are a special set of whole numbers. They can be either positive, negative or zero. Integers do not have a fractional component.

If you store an integer number in a variable, that variable is called an integer variable. Let's print some integer values.

#Integers in Python
#integers can be positive negative or zero
# < ...-3, -2, -1, 0, 1, 2, 3... >
 
int_var = 23 #23 is an integer and int_var is an integer variable
int_var1 = -23 #-23 is an integer and int_var1 is an integer variable
 
#Printing the integer value stored in variable
print(int_var)
print(int_var1)


OUTPUT:

>> 23
>> -23

Casting:

As we assign an integer number to a variable Python dynamically allocates the data type i.e. the variable is automatically declared as an integer variable, the moment you assign an integer value to it. But if you want to specify the type of a variable you can do that by casting.

For casting you can use the int() function. The int() function is a built-in function in Python. When you pass any number or a string (which resembles a number) as a parameter to the int() function It returns an integer i.e. it converts the given number or string to an integer.


The syntax of int() function is:

int(x=0, base=10)


The int() function takes two parameters:

  • x - Number or string to be converted to integer. The default value is zero.
  • base - Base of the number x.

The int() function returns:

  • An integer converted from the given number or string, default base is 10
  • If No parameters are given, returns 0
  • If base given, treats the string in the given base (0, 2, 8, 10, 16)

Further you can also check the type of the variable using the type() or isinstance() function. The type() function tells us the class type of a given object(here variable) and the isinstance() function tells us if a given object belongs to a particular class type. The isinstance() function takes two parameters the object and the class type and it returns True if the object belongs to the specified class type.

The parameters for a function are passed in between the round brackets iint(parameter). We will be discussing functions in detail later.

#Integers in Python
 
#Here we are using the int() function to specify that 23 is an integer
int_var = int(23) 
#Printing the value stored in variable
print(int_var)
#Printing the class type of the variable
print(type(int_var))
#Checking if the variable belongs to class type integer
print(isinstance(int_var, int))


OUTPUT:

>> 23
>> <class 'int'>
>> True

As we can see above the variable belongs to integer class i.e. the given variable is an integer variable.

int() function can also be used for different number systems such as binary, hexadecimal or octal.

#Integers in Python
 
#Here we are using the int() function for binary numbers
bin_int_var = '1100'
#Printing the value
print("int for 1100:", int(bin_int_var, 2))
print("int for 0b1100", int('0b1100', 2))
 
#Here we are using the int() function for octal numbers
oct_int_var = '14'
#Printing the value
print("int for 14:", int(oct_int_var, 8))
print("int for 0o14:", int('0o14', 8))
 
#Here we are using the int() function for hexadecimal numbers
hex_int_var = 'c'
#Printing the value
print("int for c:", int(hex_int_var, 16))
print("int for 0xc:", int('0xc', 16))


OUTPUT:

>> int for 1100: 12
>> int for 0b1100: 12
>> int for 14: 12
>> int for 0o14: 12
>> int for c: 12
>> int for 0xc: 12

Different ways of writing integers:

The conventional base-10 method

The conventional method of writing integers is using the base-10 decimal system, the way we have discussed above. Integers are just decimal numbers with the fractional part as zero.

#Integers in Python
 
#Here we are writing an integer using base-10 decimal system
int_var = 1234 
#Printing the value
print(int_var)
#Printing the class type of the variable
print(type(int_var))


OUTPUT:

>> 1234
>> <class 'int'>

Using underscores

Integers in Python can also be written using underscores in between i.e. the individual digits can be seperated by an underscore

#Integers in Python
 
#Here we are writing integer using underscores
int_var = 12_34_56_78 
#Printing the value
print(int_var)
#Printing the class type of the variable
print(type(int_var))


OUTPUT:

>> 12345678
>> <class 'int'>

Using different number systems

You can also write integers in Python using different number systems such as binary (base-2), octal (base-8) or hexadecimal(base-16).

#Integers in Python
 
#Here we are writing integers using different number systems
#using base-2 binary system
bin_int_var = 0b110101 
#using base-8 octal system
oct_int_var = 0o20 
#using base-16 hexadecimal system
hex_int_var = 0xFF 
 
#Printing the values
print(bin_int_var)
print(oct_int_var)
print(hex_int_var)
#Printing the class type of the variables
print(type(bin_int_var))
print(type(oct_int_var))
print(type(hex_int_var))


OUTPUT:

>> 53
>> 16
>> 255
>> <class 'int'>
>> <class 'int'>
>> <class 'int'>

Signed and unsigned integers in Python

Like C there are no signed and unsigned integer data types in Python. The int in Python acts like a signed integer. The signed integer can take both positive and negative values, whereas an unsigned integer can take only positive values.

The positive integers are stored in the memory in their binary form and the negative integers are stored in the form of 2's complement

Let's see how to convert a signed integer to an unsigned integer in Python:

To convert a signed integer to an unsigned integer we need to take the 2's complement of the number

Let's consider a signed integer number: -100

The binary representation of 100, ignoring the minus sign would be: 00000000000000000000000001100100 (32-bit representation)

Now Let's take 2's complement of the number: 11111111111111111111111110011100

Now if you take 2's complement of the above number, you get back your original number 100 and the left most leading number, 1 which is a signed bit, indicates that the number is negative

Converting the 2's complement from binary to decimal you would get: 4294967196 (signed int to unsigned int conversion)

#Signed to unsigned Integer in Python
 
#Add (2^32) to a signed integer to convert it
#to an unsigned integer
signed_integer = -100 
unsigned_integer = signed_integer+2**32 
#Printing the value
print(unsigned_integer)
 
#Add (1 << 32) to a signed integer to convert it
#to an unsigned integer
signed_integer = -200 
unsigned_integer = signed_integer+(1 << 32) 
#Printing the value
print(unsigned_integer)


OUTPUT:

>> 4294967196
>> 4294967096

** is the exponential operator in Python. It is same as multiplying x by x, y times x^y

The Bitwise left shift << operator performs bit manipulation by shifting the left operand bits of the number to the left, by the number of bits specified. It fills 0 on voids left as a result.

x << y Left shifts the integer ‘x’ with ‘y’ integer by y places. It is the same as multiplying x with 2 raised to the power of y 2**y.

Floats:

Floats are floating-point numbers in Python and they represent real numbers. These are decimal numbers where the integer and fractional part is seperated by a decimal point. They can be either positive, negative or zero.

If you store a floating-point number in a variable that variable is called a float variable. Let's print some float values.

#floats in Python
#floats can be positive negative or zero
float_var = 23.26 #23.26 is a floating-point number and float_var is a float variable
float_var1 = -23.26 #-23.26 is a floating-point number and float_var is a float variable
 
#Printing the float value stored in variable
print(float_var)
print(float_var1)


OUTPUT:

>> 23.26
>> -23.26

Casting:

As we assign a floating-point number to a variable Python dynamically allocates the data type i.e. the variable is automatically declared as a float variable the moment you assign a floating-point value to it. But if you want to specify the type of a variable you can do that by casting

For casting you can use the float() function. The float() function is a built-in function in Python. When you pass any number or a string (which resembles a number) as a parameter to the float() function it returns an float value i.e. it converts the given number or string to a floating-point number.


The syntax of float() function is:

float(x=0.0)


The float() function takes one parameters:

  • x - Number or string to be converted to float. The default value is zero.

The float() function returns:

  • A floating-point number converted from the given number or string
  • If No parameters are given, returns 0.0

#floats in Python
 
#Here we are using the float() function to specify that 23.26 is a floating-point number
float_var = float(23.26)
#Printing the value stored in variable
print(float_var)
#Printing the class type of the variable
print(type(float_var))
#Checking if the variable belongs to class type float
print(isinstance(float_var, float))


OUTPUT:

>> 23.26
>> <class 'float'>
>> True

As we can see above the variable belongs to float class i.e. the given variable is a float variable.

Different ways of writing floats:

All the different methods mentioned above, for writing integers are applicable to floating-point numbers, however the integer and the fractional part must be seperated by a decimal point for the number to be a floating-point number.

Using decimals and underscores
#floats in Python
 
#Different methods to write floats in Python
float_var = 1000.000
float_var1 = 1234.456
float_var2 = 12_34_78_56.98_34_43
 
#Printing the value stored in variables
print(float_var)
print(float_var1)
print(float_var2)


OUTPUT:

>> 1000.0
>> 1234.456
>> 12347856.983443

Using "e" notation

Floating-point numbers in Python can also be written using e notation, which stands for exponentiation.

To write a floating-point number with e notation, type a number followed by the letter e and then another number. Python takes the number to the left of the e and multiplies it by 10 raised to the power of the number after the e. So 1e8 is equivalent to 1×10^8.

Python also uses e notation to display large floating-point numbers

Float values in Python are represented as 64-bit double-precision values. The maximum value any floating-point number can be is approx 1.8 x 10^308. Any number greater than this will be indicated by inf in Python, which stands for infinity.

#floats in Python
 
#Using e notation to write floats in Python
float_var = 4e5
float_var1 = 1e-4
float_var2 = 200000000000000000.0
float_var3 = 0.00000000000000000005
float_var4 = 1.28e32
float_var5 = 1.82e308
float_var6 = -1.82e308
 
#Printing the value stored in variables
print(float_var)
print(float_var1)
print(float_var2)
print(float_var3)
print(float_var4)
print(float_var5)
print(float_var6)


OUTPUT:

>> 400000.0
>> 0.0001
>> 4e+20
>> 5e-20
>> 1.28e+32
>> inf
>> -inf

The float number 200000000000000000.0 gets displayed as 4e+20. The + sign indicates that the exponent 20 is a positive number.

Negative numbers can also be used as exponents. 1e-4 can be interpreted as 10 raised to the power -4, which is 0.0001

The float number 0.00000000000000000005 gets displayed as 5e-20. The - sign indicates that the exponent 20 is a negative number.

Float precision:

Floating-point numbers in Python can be tricky. Let's take an example, suppose we have to add two decimals, 2.2 and 4.4 the result should be 6.6, right?

We can use the boolean data type in Python to validate the expression. If the given expression is correct True is displayed or else False is displayed.

#floats in Python
 
#Let's validate the given expression
print((2.2 + 4.4) == 6.6)


OUTPUT:

>> False

So what went wrong?

Floating-point numbers are represented in computer hardware as base-2 (binary) fractions. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000.

In the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8.

These two fractions have identical values, the only real difference being that the first is written in base-10 fractional notation, and the second in base-2.

Unfortunately, most decimal fractions cannot be accurately stored in our computer as binary fractions. A consequence is that, most of the decimal floating-point numbers you enter are approximated by the binary floating-point numbers actually stored in the computer.

Let's take an example. Consider the fraction 1/3. This will give 0.33333333333... which is an infinitely long decimal and you can only approximate it as a base-10 decimal number 0.3 or 0.33 or 0.333 or so on. No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3.

In the same way, no matter how many base-2 digits you’re willing to use, the decimal value 0.1 cannot be represented exactly as a base-2 fraction. In base-2, 1/10 is an infinitely repeating fraction 0.0001100110011001100110011.... and our computer only stores a finite number of it. Stop at any finite number of bits, and you get an approximation but it will never be equal to the actual value of 1/10.

Floats are mostly approximated using a binary fraction with the numerator using the first 53 bits starting with the most significant bit and with the denominator as a power of two. In the case of 1/10, the binary fraction is 3602879701896397 / 2 ** 55 which is close to but not exactly equal to the true value of 1/10. The numbers 0.1 and 0.10000000000000001 and 0.1000000000000000055511151231257827021181583404541015625 are all approximated by 3602879701896397 / 2 ** 55. Since all of these decimal values share the same approximation, any one of them could be displayed

#floats in Python
 
#importing the decimal module
import decimal
 
print(0.3)
print(1/3)
print(decimal.Decimal(1/3))#Exact decimal representation
 
print(1/10)
print(decimal.Decimal(1/10)) #Exact decimal representation
 
print(3602879701896397 / 2 ** 55)
print(decimal.Decimal(3602879701896397 / 2 ** 55)) #Exact decimal representation


OUTPUT:

>> 0.3
>> 0.3333333333333333
>> 0.333333333333333314829616256247390992939472198486328125
>> 0.1
>> 0.1000000000000000055511151231257827021181583404541015625
>> 0.1
>> 0.1000000000000000055511151231257827021181583404541015625

Hence, this is not an error in Python, this is the very nature of binary floating-point. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine.

If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display 0.1000000000000000055511151231257827021181583404541015625, as shown above. That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead 0.1.

Just remember, Even though the printed result looks like the exact value of 1/10, the actual stored value is the nearest representable binary fraction.

To limit the fractional numbers after the decimal point you can use the round function in Python. The round function has it's own limitations which we will discuss when we will be looking at built-in functions in Python

#floats in Python
 
#Now if we check the result of the expression, we can see
print(2.2 + 4.4)
#we can use the round function to limit the fractional numbers
print(round(2.2 + 4.4, 2)) #2 numbers after decimal point
#Now if we validate the expression again with the round function we get
print(round(2.2 + 4.4, 2) == 6.6)


OUTPUT:

>> 6.6000000000000005
>> 6.6
>> True

Python Decimals:

To overcome the precision problem with floats, we can use the decimal module in Python. While floating-point numbers have precision up to 15 decimal places, the precision value for decimal module is variable and can be set by the user.

To use a module we need to import the module first. We will be discussing modules in detail later.

#decimals in Python
 
#importing the decimal module
import decimal
 
#Difference between float and decimal
print(0.1) #float number
print(decimal.Decimal(0.1)) #decimal number
 
#operations performed on decimal numbers
print(2.2 + 4.4) #adding float number
print(decimal.Decimal(2.2) + decimal.Decimal(4.4))
print(decimal.Decimal('2.2') + decimal.Decimal('4.4'))
print(decimal.Decimal(1.300) + decimal.Decimal(1.200))
print(type(decimal.Decimal(0.1)))


OUTPUT:

>> 0.1
>> 0.1000000000000000055511151231257827021181583404541015625
>> 6.6000000000000005
>> 6.600000000000000532907051820
>> 6.6
>> 2.500000000000000000000000000
>> <class 'decimal.Decimal'>

The precision can be set by the user using the .prec property of the .getcontext() function from the decimal module.

#decimals in Python
 
#importing the decimal module
import decimal
 
#Setting the precision value for a decimal number
print(1/7) #float number
 
print(decimal.Decimal(1) / decimal.Decimal(7)) #decimal number
 
#Setting precision value using getcontext()
decimal.getcontext().prec = 5 #precision=5 means only 5 numbers after decimal point 
print(decimal.Decimal(1) / decimal.Decimal(7)) #decimal number


OUTPUT:

>> 0.14285714285714285
>> 0.1428571428571428571428571429
>> 0.14286

The trailing zeros are always preserved in decimal numbers to indicate significance.

The decimal module is used when we want to carry out decimal calculations just like schoolbooks.

Decimal is preferred in accounting applications where we need exact decimal representation.

When we want to control the level of precision required and we want to preserve the significant decimal places, we tend to use the decimal module.

However floating-point numbers are mostly preferred over decimal numbers due to their efficiency. As floating-point calculations are much faster than decimal calculations

Python Fractions:

Python has a built-in fractions module which lets us perform operations involving fractional numbers

A fraction has a numerator and a denominator, both of which are integers.

The fractions module supports different arithmetic operations on rational numbers.

Let's have a look at some fractions.

#fractions in Python
 
#importing the fractions module
import fractions
 
#printing the values
print(fractions.Fraction(1.5))
print(fractions.Fraction(4))
print(fractions.Fraction(1,3))
 
#the fractions module also supports different operations
print("Addition:",fractions.Fraction(1,3) + fractions.Fraction(1,3)) #Addition
print("Multiplication:",fractions.Fraction(7,8) * fractions.Fraction(7,12)) #Multiplication
print(1 / fractions.Fraction(7,8))
print("Exponentiation:",fractions.Fraction(7,8) ** fractions.Fraction(7,12)) #exponentiation
print(fractions.Fraction(-3,9) > 0) #if greater than zero: True, or else: False
print(fractions.Fraction(-3,9) < 0)
print(type(fractions.Fraction(1.5)))


OUTPUT:

>> 3/2
>> 4
>> 1/3
>> Addition: 2/3
>> Multiplication: 49/96
>> 8/7
>> Exponentiation: 0.9250631140755854
>> False
>> True
>> <class 'fractions.Fraction'>

While creating fractions from floats, we might get some unusual results. This is due to the imperfect binary floating point number representation as discussed above.

Fractions module also allows us to create fractions from strings. This is the preferred option when using decimal numbers as strings give a better representation of fractional numbers.

#fractions in Python
 
#importing the fractions module
import fractions
 
#printing the values
print(fractions.Fraction(2.13))
print(fractions.Fraction('2.13')) #string to fraction
 
print(fractions.Fraction(7/62))
print(fractions.Fraction('7/62')) #string to fraction


OUTPUT:

>> 2398166801574789/1125899906842624
>> 213/100
>> 8135534810733799/72057594037927936
>> 7/62

To print the numerator and denominator seperately the fractions module has two properties .numerator and .denominator. It also has a .limit_denominator() method which helps to perform rational approximation for a given floating point number.

#fractions in Python
 
#importing the fractions module
import fractions
 
#printing the values
print(fractions.Fraction('7/62').numerator) #for numerator
print(fractions.Fraction('7/62').denominator) #for denominator
print(fractions.Fraction('2.13').numerator)
print(fractions.Fraction('2.13').denominator)
 
print(fractions.Fraction(3.14159265358979323846))
print(fractions.Fraction('3.14159265358979323846'))
print(fractions.Fraction('3.14159265358979323846').limit_denominator(100))
print(fractions.Fraction('3.14159265358979323846').limit_denominator(10))


OUTPUT:

>> 7
>> 2
>> 213
>> 100
>> 884279719003555/281474976710656
>> 157079632679489661923/50000000000000000000
>> 311/99
>> 22/7

Note that the .numerator and .denominator properties don't need any parantheses after them as they don't perform any action they just return information.

Complex numbers:

Python provides built-in support for complex numbers

Complex numbers have two distinct components a real part and an imaginary part

Complex numbers are mostly used for scientific computing

To create a complex number in Python, you simply write the real part, then a plus sign, then the imaginary part with the letter j at the end

#Complex numbers in Python
 
complex_var = 1+2j
complex_var1 = -1+2j
complex_var2 = -1-2j
 
#Printing the values
print(complex_var)
print(complex_var1)
print(complex_var2)
print(type(complex_var))


OUTPUT:

>> (1+2j)
>> (-1+2j)
>> (-1-2j)
>> <class 'complex'>

We can seperate the real and imaginary part of a complex number by using two properties of the complex numbers class .real and .imag

Note that the .real and .imag properties don't need any parantheses after them as they don't perform any action they just return information

#Complex numbers in Python
 
complex_var = 1+2j
#Printing the values
print(complex_var)
print(complex_var.real)
print(complex_var.imag)


OUTPUT:

>> (1+2j)
>> 1.0
>> 2.0

Note that the real and imaginary values returned are floats, even though we specified integers

Complex numbers have a conjugate method that returns complex conjugate of the given complex number

#Complex numbers in Python
 
complex_var = 1+2j
#Printing the values
print(complex_var)
print(complex_var.conjugate())


OUTPUT:

>> (1+2j)
>> (1-2j)

For any complex number, its conjugate is the complex number with the same real and imaginary part but with the opposite sign. So in this case, the complex conjugate of 1 + 2j is 1 - 2j.

Interestingly, int and float also have .real and .imag properties as well as the .conjugate() method.

#Complex numbers in Python
 
#for integers
int_var = 23
print(int_var.real)
print(int_var.imag)
print(int_var.conjugate())
 
#for floats
float_var = 35.26
print(float_var.real)
print(float_var.imag)
print(float_var.conjugate())


OUTPUT:

>> 23
>> 0
>> 23
>> 35.26
>> 0.0
>> 35.26

For floats and integers, .real and .conjugate() always return the number itself, and .imag always returns 0. One thing to notice, is that var.real and var.imag return an integer if var is an integer and a float if var is a float.

If you are learning Python for data science, web development, machine learning or general programming you may never need to use complex number.

Complex numbers are mostly used in the domains related to scientific computing and computer graphics.

Type conversion:

You can convert from one type to another with the int(), float(), and complex() functions in Python.

#Type conversion in Python
 
#Declaring variables
int_var = 23 #integer variable
float_var = 25.26 #float variable
complex_var = 2j #complex variable
string_var = "9867" #complex variable
 
#Converting from one type to another
#integer to float conversion
int_to_float = float(int_var) #Using float() function
print("integer:", int_var)
print("integer to float:", int_to_float)
 
#string to float conversion
str_to_float = float(string_var) #Using float() function
print("string to float:", str_to_float)
print("string to float (infinity):", float('infinity'))
print("string to float (nan - not a number):", float('nan'))
 
#float to integer conversion
float_to_int = int(float_var) #Using int() function
print("float:", float_var)
print("float to integer:", float_to_int)
 
#string to integer conversion
str_to_int = int(string_var) #Using int() function
print("string to integer:", str_to_int)
 
#integer to complex conversion
int_to_comp = complex(int_var) #Using Complex() function
print("integer:", int_var)
print("integer to complex:", int_to_comp)
 
#complex to integer conversion
comp_to_int = int(complex_var) #Using int() function
print("complex:", complex_var)
print("complex_to_integer:", comp_to_int)


OUTPUT:

>> integer: 23
>> integer to float: 23.0
>> string to float: 9867.0
>> string to float (infinity): inf
>> string to float (nan - not a number): nan
>> float: 25.26
>> float to integer: 25
>> string to integer: 9867
>> integer: 23
>> integer to complex: (23+0j)
>> TypeError: can't convert complex to int

  • The float value for string infinity is inf, which stands for "infinity".
  • The float value for string nan is nan, which stands for "not a number".
  • You cannot convert from complex to int or float types.

  • Note that '24'≠24, here former is a string while latter is an integer number.
  • You can convert from string to integer or float type only if that string resembles a number for e.g. '24', '720', etc.

Number systems:

There are four different number systems in python. These number systems represent the numbers in computer architecture

  • Binary number system (base-2) [only possible digits: 0s and 1s]
  • Octal (base-8) [possible digits: 0 to 7]
  • Hexadecimal (base-16) [numbers can be represented using digits from 0 to 9 and letters a to f]
  • Decimal (base-10) [possible digits: 0 to 9]

We have already discussed how to write different number systems in python here.

Number systems conversion:

Let's have a look at how to convert from one number system to another in python.

  • To convert from decimal to binary we can use the bin() function.
  • To convert from decimal to octal we can use the oct() function.
  • To convert from decimal to hexadecimal we can use the hex() function.

In python, Binary numbers have 0b as the prefix whereas, Octal and Hexadecimal numbers have 0o and 0x as the prefix respectively.

#Number systems conversion in Python
 
#Binary to Decimal
bin_var = 0b1011 #binary number
print("1011(binary) to decimal:", bin_var)
 
#Decimal to Binary
dec_var = 67 #decimal number
print("67(decimal) to binary:", bin(dec_var))
 
#Octal to Decimal
oct_var = 0o1234 #octal number
print("1234(octal) to decimal:", oct_var)
 
#Decimal to Octal
dec_var = 87 #decimal number
print("87(decimal) to octal:", oct(dec_var))
 
#Hexadecimal to Decimal
hex_var = 0xCC #hexadecimal number
print("0xCC(hexadecimal) to decimal:", hex_var)
 
#Decimal to Hexadecimal
dec_var = 97 #decimal number
print("97(decimal) to hexadecimal:", hex(dec_var))
 
#Float to Binary
float_var = 24.26 #float number
print("24.26(float) to binary:", bin(float_var))


OUTPUT:

>> 1011(binary) to decimal: 11
>> 67(decimal) to binary: 0b1000011
>> 1234(octal) to binary: 668
>> 87(decimal) to octal: 0o127
>> 0xCC(hexadecimal) to decimal: 204
>> 97(decimal) to hexadecimal: 0x61
>> TypeError: 'float' object cannot be interpreted as an integer

As you can see above there is no built-in function to convert from float to binary, octal or hexadecimal number, only integer numbers can be converted. If you try to convert a floating-point number you will get a Type error.

Float to binary conversion:

Since there is no built-in function in python to convert from float to binary we can write a simple code of ours which contains two user-defined functions. The float_to_bin() function converts a floating-point number to binary and the int_to_bin() function converts an integer number to binary.

Note that here we are not using the built-in function bin() to convert from integer to binary, instead we have written our own function int_to_bin().

To convert a floating-point number to binary we need to split the integer and fractional parts, then convert each of them to binary seperately, and finally join the two binary parts, seperated by a decimal point, to get the desired binary representation

If the floating-point number is negative, the sign is preserved in the final converted output.

#Program to convert floating-point number to binary
  
#Function returns binary representation
#for a floating-point number
def float_to_bin(number, places=3):
	abs_num = abs(number)
	#seperate the integer and fractional part
	integer, dec = int(abs_num), abs_num%1
	#convert the integer part to binary
	#add decimal point and negative sign
	#if the floating-point number inputted is negative
	res = int_to_bin(integer) + "." if number>0 else "-" + int_to_bin(integer) + "."
 
	#iterate for the given number of decimal places
	for _ in range(places):
		#keep multiplying the decimal value by 2
		dec *= 2
		#seperate the integer and fractional part
		integer, dec = int(dec), dec%1
		#keep adding the integer part to the result
		res += str(integer)
	return res
 
#Function returns binary representation for an integer number
def int_to_bin(num):
	bin_str = ""
	while num >= 1:
		#Divide the number by 2 and
		#keep adding remainder to
		#the binary string
		bin_str += str(num%2)
		#First divide the number by 2
		#then keep dividing the quotient by 2
		num //= 2
	return bin_str
 
#Take the user input as absolute value of the floating-point number
n = float(input("Enter your floating point value : \n"))
 
#Take user input for the number of decimal places user want in the result
p = int(input("Enter the number of decimal places of the result : \n"))
 
#Calling the function
print(float_to_bin (n, places = p))


OUTPUT:

>> Enter your floating point value :
>> 8.234
>> Enter the number of decimal places of the result : 
>> 4
>> 0001.0011

Similary, you can write your own code to convert from float to octal or hexadecimal.

We will be discussing loops, functions and mathematical operations in python in further articles.

Size in memory:

Let's see how much memory do these different numeric types require and which one of these can be efficiently used when you have to store large numbers with a limited memory.

We can use the sys module for this purpose. sys is a built-in module in Python and has a method .getsizeof() which gives us the size of any an object in the memory.

#Memory size for different objects
 
#importing modules
import decimal, sys
 
int_var = 0
int_var1 = 5
int_var2 = 2**64
float_var = 5.2
float_var1 = 2**64.2
decimal_var = decimal.Decimal(5.2)
 
#Printing the memory size values
print("size of int():", sys.getsizeof(int()))
print("size of integer (0):", sys.getsizeof(int_var))
print("size of integer (5):", sys.getsizeof(int_var1))
print("size of integer (2**64):", sys.getsizeof(int_var2))
 
print("size of float():", sys.getsizeof(float()))
print("size of float (5.2):", sys.getsizeof(float_var))
print("size of float (2**64.2):", sys.getsizeof(float_var1))
 
print("size of decimal (5.2):", sys.getsizeof(decimal_var))


OUTPUT:

>> size of int(): 24
>> size of integer (0): 24
>> size of integer (5): 28
>> size of integer (2**64): 36
>> size of float(): 24
>> size of float (5.2): 24
>> size of float (2**64.2): 24
>> size of decimal (5.2): 104

As we can see above the size of integer 0 is 24 bytes that means Python uses 24 bytes to store the number 0, but number zero requires only 1 bit. So we can say that 24 bytes are an overhead to store an integer object. We can see that above, since the size an empty integer object int() is also 24 bytes. The next 4 bytes are used to represent 5 in the memory, since the size of 5 is 28 bytes.

In Python, value of an integer is not restricted by the number of bits and can expand to the limit of the available memory. Thus we never need any special arrangement for storing large numbers.

The size of an empty Float object float() is 24 bytes. Float uses 24 bytes to store 5.2 at the same time decimal uses 104 bytes to store the same number 5.2.

To store 2**64 int uses 36 bytes whereas float uses 24 bytes. So we can clearly see that using float to store large decimal numbers is much efficient.

Conclusion

In this article, we looked at Numbers Data type in Python. We looked at different numeric types and understood every numeric type in detail. We also discussed how much memory does each numeric type occupy. We also looked at how to convert from one numeric type to another using built-in functions in Python. We also looked at the efficiency of each numeric type and their representation in the memory.