Python – Numeric Types – float and complex Classes

In our previous article we have discussed about int Class which deals with Integer numbers. In this Article, I will explain float and complex classes. And these classes deals with floating point numbers and complex numbers respectively.

float Class – Deals with Floating point numbers

We can create floating point numbers using float() constructor. We can also use the floating point numbers directly and Python treat them as an objects of float Class.

float() constructor takes a single optional argument to create an object with floating point number as it’s value. The argument can be a number or a string. If NO value passed to the argument; it treats as the value “0.0”. Below are the examples to create float objects.

>>> 2.3
>>> type(2.3)
<type 'float'>
>>> float(5.7)
>>> float("9.3")

complex Class – Deals with Complex numbers

The objects of complex class can be created using complex() Class constructor or directly by giving the complex value. Complex numbers have real and imaginary parts. The value (2+3j) is a complex number; where 2 is the real part and 3 is the imaginary part.

>>> 2+3j
>>> (2 + 3j)

The Syntax of the constructor is:

complex(x, y)

Where x is the real part and y is the imaginary part. Both these arguments are optional. If you do not pass any arguments Python creates an object with the complex value 0j.

>>> complex()
>>> complex(2)
>>> complex(2, 3)

First argument will be a number or a string. If you pass a string in the first argument; it doesn’t allow to take the second argument.

>>> complex("2")

If you try to pass a second argument, passing a string through first argument; Python will throw the Error.

>>> complex("2", 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: complex() can't take second arg if first is a string

You can give complete complex number in a string form through it’s first argument. When you pass a complex number as a string, spaces are not allowed between the number and the “+” sign. That means, you can pass it as “2+3j”; NOT “2 + 3j”. If you pass an invalid string, Python will throws the Error.

>>> complex("2+3j")
>>> complex("2 + 3j")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string

As complex numbers have real and imaginary parts, sometimes it is required to access these parts separately from the complex number. complex class provides real and imag properties to get real and imaginary parts of the complex number respectively.

>>> c = complex(2,3)
>>> c
>>> c.real
>>> c.imag

We will discuss more topics as we go.


Python – Numeric Types – float and complex Classes

Leave a Reply

Your email address will not be published.

Scroll to top