Python numbers are an essential part of any programmer’s basic toolkit. Many consider mastering this data type essential to refining your code and turning it into syntactic perfection.
As we mentioned in our Python Data Types piece, integers, floating-point numbers, and complex numbers are used to solve mathematical problems of arithmetic, geometric and statistical nature.
Today we’ll take a closer look at Python’s basic mathematical building blocks and their classification:
Python Integer
Simply put, Integers are numbers with no decimal places (whole numbers). Like in math, whole numbers can be positive or negative with no fractional component.
For instance:
-1,0,1,2,33,1000 are all ints
While
-1.0, 0.0, 0.5, 1.1, 1.564, 2.7, 23.67 are not
In Python, integers are commonly known as ints, and such data types are marked with the int syntax in your code. You can easily spot them every time you see a number without decimals.
Recognizing Data Types with Python Type Function
Using the type function to double-check your variable’s data type can save you considerable time and confusion, especially if you’re still learning the ropes.
You can create an integer by typing a whole number and assigning a said number to a variable. But let’s say that for whatever reason, you’re not sure which type of data you’re dealing with and want to check how Python recognizes your input.
That’s where one of Pythons coolest built-in functions come into play, The Type function: type ( )
Example:
a = 18
Python interpreter evaluates inputs line by line. Once you’ve typed your variable and assigned its value (using the equal sign, known as the assignment operator in Python), you can hit the enter key on your keyboard to take you down to the next line of code.
In detail, this code tells the computer to set aside a box in memory, label it as “a”, and then put a whole number (in this case ten) into that box.
Now that you’ve assigned a value to your variable, you can now order Python to print the type function of “a” by putting the “a” variable inside its parenthesis as follows:
a = 18 print(type(a))
Every time you use print(type ( )) in your code and run your code, you’re guaranteed to get a return value (known as output) that specifies which Data Type you’re dealing with.
The Terminal shows after running the program:
<class 'int'>
Notice how Python gives you a return value that specifies your variables classification (between a couple of angled brackets). This means that the variable “a” is of class int, as it holds an integer (a whole number without a decimal part) as its value.
You might be wondering: how do you type an integer that goes above three figures in magnitude?
Normally, you’d use commas to separate digits, but in Python, commas are used to separate values within strings or lists (more on those Data Types later).
To avoid any unnecessary confusion, you can place underscores where commas used to be.
Example:
Normally: 1,000
In Python: 1_000
But, what if you need to process decimal numbers? That’s where float data type comes in!
Python Floating Point
Floats are numbers (negative or positive) that have decimal values. Unlike integers, they show a decimal part (even if it is valued at zero).
For instance,
-1.0, 0.0, 0.5, 1.3, 1.364, 2.5, 24.72 are all floats
In Python, floats are also known as floating-point numbers, and such data types are marked with the float syntax in your code.
Example:
a = 61.0 print(type(a))
If you assign a floating-point number to a variable and then print the type function of “a”, Python will specify (in between a couple of angled brackets) that “a” is of class float.
This means that “a” holds a floating-point number (a number with a decimal part) as its value.
The Terminal shows after running the program:
<class 'float'>
Let’s say you want to type in a number that’s incredibly large in magnitude:
You’re right to think that entering numbers in the order of hundreds of millions (or billions) would be incredibly annoying. Even if you copy-paste them from other files, this can make your code look messy and difficult to read.
Thankfully, you can significantly reduce their visual footprint by using scientific notation.
Let’s say you want to express a number in the millions:
Normally you’d type: 5,289,000
In Python, you can enter this number as follows: 5_289_000 or 5289000
Even better, you can significantly reduce it by using Scientific Notation: 5.289e+6
As you’ve probably noticed, applying scientific notation is made possible by numeric types such as floats.
Let’s use scientific notation and see if Python recognizes “a” as a float!
a= 5.289e+6 print(type(a))
The Terminal shows after running the program:
<class 'float'>
Representing Ints into Floats and Vice versa
As mentioned in our article 11 Concepts Every Successful Programmer Should Know, another way to look at specific Data Types is by their mutability or immutability.
All data types are stored in a computer’s memory for processing. Some can be modified during processing (hence they are considered mutable), while others can’t be altered once they’re stored in memory (immutable).
Numeric types such as ints and floats are immutable. In other words, integers and floating-point numbers can’t be changed once created. But that doesn’t mean you can’t represent a number in different forms!
Python is one of the most versatile programming languages out there. You can use operators and functions to produce different outputs. Still, you can also represent one data as another by calling in the specific function of a data type on any number or variable that you’d like.
For Numeric types, using int( ) on a number with a decimal value will reproduce only the whole part of that number. Likewise, using float ( ) on a whole number will represent it in its decimal version:
Example:
Assigning twenty-three point eight to our variable “a” and calling Python to print an integer of “a”.
a = 23.8 print(int(a))
The Terminal shows after running the program:
23
Changing “a” to forty-five and calling to print a float.
a = 45 print(float(a))
The Terminal shows after running the program:
a = 45.0
Changing “a” to a hundred thousand in scientific notation and calling to print an integer.
a = 1e6 print(int(a))
The Terminal shows after running the program:
1000000
Changing “a” to a hundred thousand in scientific notation but calling to print a float.
a = 1e6 print(float(a))
The Terminal shows after running the program:
1000000.0
Applying Basic Operators on ints and floats
Both Integer (ints) and floating-point numbers (floats) represent numbers essential for running basic math and complex calculations.
Python automatically interprets adding, subtracting, multiplying, dividing, and powering using the same operators you’d use on a calculator. We can go through some easy examples to demonstrate how that would look on Python’s shell:
Adding, Subtracting, Multiplying, and Dividing ints
Let’s assign ten and twenty as the respective values of “a” and “b” and call the print function on some basic math for them:
a=15 b=25 print(a+b) print(a-b) print(a*b) print(a/b) print(a+100) print(b*10) print(b/2)
The Terminal shows after running the program:
40 -10 375 0.6 115 250 12.5
Adding, Subtracting, Multiplying, and Dividing floats
Let’s assign different variables with different numeric type values to each and run some math operators between them.
a=15 b=25 c=7.5 d=12.5 e=2.7e10 print(c+d) print(d-c) print(c+e) print(e/c) print(c*d) print(a+b+c) print(a*c) print(b/c) print(a-b-c)
The Terminal shows after running the program:
20.0 5.0 27000000007.5 3600000000.0 93.75 47.5 112.5 3.3333333333333335 -17.5
Floats vs Integers
Here’s a list of key takeaways when comparing floats vs integers:
- Integers are positive or negative numbers with no decimal places (whole numbers). Example: -1,0,1,2,55,1000
- Floats are positive or negative numbers that have a decimal or fractional component. Example: -1.0, 0.0, 0.5, 1.1, 1.354, 2.2, 25.99
- Thanks to floats, we can use scientific notation in Python.
- You can operate both data types, regardless of their classification. In other words, you can add, subtract, multiply, divide, power up, ints, and floats just as you would on a calculator.
- You can also call the type function directly on a float or int and any variable that holds them.
Python Complex Numbers
Unlike many programming languages used today, Python complex numbers actually come with built-in support. The wildly popular Cmath module allows you to apply advanced functions to your complex numbers, making it a great alternative to MATLAB.
Just type the following into your file:
# importing “cmath” for complex number operations import cmath
As you might recall from our recent Python data types piece, complex numbers are expressed as a sum of real and imaginary components. By appending the letter “j” to a number, you’re telling Python that your expression is a complex number. Here’s a quick example:
z=2+5j
Python deviates from the traditional notation for complex numbers, using “j” instead of “i”. Python’s creator believes that the letter “i” looks too much like a lowercase L, which could lead to all sorts of confusion.
Notice that removing the “j” changes your expression’s type, turning it into an integer result.
z = 2 + 5 print (type(z)) <class 'int'>
This also means you must append a letter j to your floating-point numbers to turn them into complex expressions.
z = 2.13 + 5.84j print (type(z)) <class 'complex'>
You can also ask Python to return your complex number’s real and imaginary components using the .real and .imag attributes.
z = 2 + 5j print (z.real) 2.0 z = 2 + 5j print (z.imag) 5.0
Keep in mind that complex numbers are immutable, so you’re only able to access your complex number attributes, but you can’t assign new values to them.
Another way to define Python complex numbers is with the built-in complex () function. It’s an alternative to the literal expression we’ve been using so far. Here’s what it looks like:
z = complex (2,5)
We can call in the type function to double-check that our expression is a complex number. Give it a try!
z = complex (2,5) print (type(z)) <class 'complex'>
The first value corresponds to the real part, and the second represents your complex number’s imaginary part. Both expressions work, and it’s ultimately up to you to use whatever feels right and looks clean in your source code.
Now that we understand that Python complex numbers are immutable numeric data, it’s time we take a look at some of the most common functions we can use to solve problems.
Python Complex Numbers Common Functions
Now that we’ve covered the different ways you can express complex numbers, it’s time we take a closer look at some of the most widely-used functions for Python complex numbers.
Addition and Subtraction
One of the most common functions is plain-old Addition. Python can sum up any number of complex numbers by adding their real and imaginary components.
z1 = 2 + 5j z2 = 3 + 7j print (z1+z2) (5+12j)
def addComplex (z1, z2): return z1+z2 z1 = complex (2,5) z2 = complex (3,7) print ("Result : ", addComplex (z1,z2)) Result : (5+12j)
Similarly, you can subtract Python complex numbers as follows:
z1 = 2 + 5j z2 = 3 + 7j print (z1-z2) (-1-2j)
def subComplex (z1, z2): return z1-z2 z1 = complex (2,5) z2 = complex (3,7) print ("Result : ", subComplex (z1,z2)) Result : (-1-2j)
Multiplication and Division
Dividing and multiplying Python complex numbers is a straightforward process. You can also use the literal format or corresponding function.
z1 = 2 + 5j z2 = 3 + 7j print (z1 * z2) (-29+29j)
def mulComplex (z1, z2): return z1*z2 z1 = complex (2,5) z2 = complex (3,7) print ("Result : ", mulComplex (z1,z2)) Result : (-29+29j)
Here’s a basic Python complex numbers division:
z1 = 2 + 5j z2 = 3 + 7j print (z1 / z2) (0.706896551724138+0.01724137931034482j) def divComplex (z1, z2): return z1/z2 z1 = complex (2,5) z2 = complex (3,7) print ("Result : ", divComplex (z1,z2)) Result : (0.706896551724138+0.01724137931034482j)
Exponentiation for Python Complex Numbers
Python also allows you to find the exponential of any Python complex number.
# importing “cmath” for complex number operations import cmath print (cmath.exp(3 + 7j)) (15.142531566086864+13.195928586605717j)
Using Python Complex Numbers in Coordinate Plane
Python complex numbers can also be visualized in the coordinate plane, with the X-axis representing the real component and the Y-axis representing the imaginary part. You can then plot your data to get a visual representation of a two-dimensional vector.
Plotting your data is a topic worth its own in-depth discussion, but it’s worth noting that vectors and complex numbers work similarly, and it’s hands down one of the coolest uses Python complex numbers has to offer.
Advanced Python Complex Number Functions
Among the most advanced Python complex number functions, you’ll find Logarithmic, Trigonometric and Hyperbolic functions.
Let’s start with the Logarithmic function for Python complex numbers.
# Step 1: Import cmath for complex numbers operations. import cmath import math # Step 2: Define your complex numbers real and imaginary components a = 3.0 b = 7.0 # Step 3: Define "z" as a complex number z = complex(a, b); # Complex Exponentiation print ("Complex Exponentiation result:" , (cmath.exp(z))) # Complex Logarithm print ("Complex Logarithm result:" , (cmath.log(z,10))) Complex Exponentiation result: (15.142531566086864+13.195928586605717j) Complex Logarithm result: (0.8817139967814686+0.5063459083693581j)
Cmath also supports trigonometric functions, and they’re used to solve mathematical problems.
# Step 1: Import cmath for complex numbers operations. import cmath # Step 2: Define your complex numbers real and imaginary components a = 3.0 b = 7.0 # Step 3: Define "z" as a complex number z = complex(a, b); # Printing the Sine of the Complex Number print ("Sine of z result:" , (cmath.sin(z))) # Printing the Cosine of the Complex Number print ("Cosine of z result:" , (cmath.cos(z))) # Printing the Tangent of the Complex Number print ("Tangent of z result:" , (cmath.tan(z))) Sine of z result: (77.37850442046603-542.8288478055589j) Cosine of z result: (-542.8297505618626-77.37837573567569j) Tangent of z result: (-4.646832806149714e-07+0.9999984031828296j)
# Step 1: Import cmath for complex numbers operations. import cmath # Step 2: Define your complex numbers real and imaginary components a = 3.0 b = 7.0 # Step 3: Define "z" as a complex number z = complex(a, b); # Printing the Sine of the Complex Number print ("Arcsine of z result:" , (cmath.asin(z))) # Printing the Cosine of the Complex Number print ("Arccosine of z result:" , (cmath.acos(z))) # Printing the Arctangent of the Complex Number print ("Arctangent of z result:" , (cmath.atan(z))) Arcsine of z result: (0.40179816285146036+2.7263424970102745j) Arccosine of z result: (1.1689981639434364-2.7263424970102745j) Arctangent of z result: (1.5183578574297796+0.12094923784451785j)
Python Hyperbolic Functions
Python and its Cmath module can also calculate hyperbolic functions in mathematical applications.
# Step 1: Import cmath for complex numbers operations. import cmath # Step 2: Define your complex numbers real and imaginary components a = 3.0 b = 7.0 # Step 3: Define "z" as a complex number z = complex(a, b); # Printing the Sine of the Complex Number print ("Hyperbolic sine of z result:" , (cmath.sinh(z))) # Printing the Cosine of the Complex Number print ("Hyperbolic cosine of z result:" , (cmath.cosh(z))) # Printing the Tangent of the Complex Number print ("Hyperbolic tangent of z result:" , (cmath.tanh(z))) Hyperbolic sine of z result: (7.552498491503594+6.61431901165645j) Hyperbolic cosine of z result: (7.59003307458327+6.581609574949268j) Hyperbolic tangent of z result: (0.9993103079835998+0.00490758339523229j)
# Step 1: Import cmath for complex numbers operations. import cmath # Step 2: Define your complex numbers real and imaginary components a = 3.0 b = 7.0 # Step 3: Define "z" as a complex number z = complex(a, b); # Printing the Sine of the Complex Number print ("Inverse hyperbolic sine of z result:" , (cmath.asinh(z))) # Printing the Cosine of the Complex Number print ("Inverse hyperbolic cosine of z result:" , (cmath.acosh(z))) # Printing the Tangent of the Complex Number print ("Inverse hyperbolic tangent of z result:" , (cmath.atanh(z))) Inverse hyperbolic sine of z result: (2.7203975979400625+1.162755246722785j) Inverse hyperbolic cosine of z result: (2.7263424970102745+1.1689981639434364j) Inverse hyperbolic tangent of z result: (0.05102383908587882+1.4503730991741908j)
Depending on what kind of application you’re looking to develop, you might find some of these advanced Python complex numbers functions to be quite useful.
Nonetheless, if you wish to keep all your code and work in Python and avoid MATLAB altogether, the Cmath module is an excellent and easy-to-import option that is one line of code away.
Summarizing
Just as you can calculate and operate numbers in a calculator or organize ideas with proper grammar and syntax when you’re writing an email, you can also use python data types, their operators, and functions as the building blocks of your code and programs.
Each data type offers a unique set of advantages and possibilities that are up to you, the programmer, to implement and exploit for maximum efficiency.
As we delve deeper into the maths surrounding Python, we’ll uncover new and exciting possibilities that cement the language as one of the most versatile and easy to learn today.