Working With Floats
One limitation of range
is that is can only work with integers, which are positive or negative whole numbers. If you need to generate a list of floats, which are numbers with a decimal portion, then you can use NumPy. To confirm that you have NumPy installed, drop into a Python shell and run the following:
>>> import numpy
00:00
One limitation of the range()
function is that it can only work with integers, aka positive or negative whole numbers. If we need to generate a list of floats, which are numbers with a decimal portion, we can use NumPy, a popular Python library for dealing with advanced numerical operations.
00:25
NumPy can be obtained with pip
, pip install numpy
.
00:32
To confirm that you have it installed, drop into a Python shell and run import numpy
. If you get a ModuleNotFoundError
, then it’s not installed or it’s not installed for the version of Python you’re using.
00:50
Once it’s installed, we can utilize the arange()
function to generate what’s called an NDarray of values. We’ve got an entire tutorial on the arange()
function, and I have a module on NumPy as a part of my Matplotlib course, so if you’re interested in learning more about this, I’ll have links to both those resources down below in the video notes.
01:18 You can think of an NDarray as similar to a Python list, except it’s immutable, meaning that it can’t be edited after it’s created—among some other differences.
01:33
The arange()
function will allow us to generate an NDarray of numbers, and unlike the range()
function, it supports floating-point numbers.
01:45
Let’s take a look. I’m here in a blank Python file and I’m going to start by importing numpy
as np
. Now I’ll say for i in np.arange()
, passing in 0.3
for the start
, 1.6
for the stop
, and 0.3
for the step
. For our purposes, this is equivalent to what we were doing before, using vanilla Python, but now we can generate collections of floats too.
02:22
And as usual, we’ll print i
on each iteration.
02:28 I will run this, and you see something a little bit strange is going on. For some reason, one of the values in our generated NDarray is 0.89 repeated. These sorts of very small errors can happen from time to time, and they are a direct result of the fact that computers have trouble storing decimal floating-point numbers as binary values.
02:59 These errors are typically around the 16th decimal place, and so for most purposes, they don’t pose a real issue, but if you’re calculating something like satellite orbital trajectories, they can be problematic.
03:15
The simplest way to solve this issue is to use the built-in decimal
library, which will allow you to generate floating-point numbers exactly—but at the cost of performance.
03:28 To learn more about this library and some of the technical reasons behind this issue, see the video notes down below.
Become a Member to join the conversation.
sroux53 on May 18, 2020
Excellent !