Monday, May 4, 2015

Python Decimal Module - Python Numbers - Python Tutorial

Python Decimal ModulePython Decimal Module


In the previous two Python tutorials, we looked at issues that arise when working collaboratively with floating point numbers in the Python programming language. When working with floating point numbers we have seen that Python sometimes returns a value that we are not suspecting. This is doesn’t happen often but when we get a number that is a few ten thousandths off this can be concerning especially if you are working with numbers that need to have precise returns like a accounting program or a program that controls trajectory of a spacecraft. It would be concerning if we could not get the correct amount of money or if our spacecraft was off course by a tad bit we would probably miss the earth on the return and fly right into the sun.

In this tutorial, we are going to look at the Python decimal module which needs to import into your program for the functions to work. Decimals are basically floating point numbers but, they have fixed number of decimal points.  We can think of them as fixed-precision floating point numbers. We can also control how Python rounds the numbers unlike with the round() function where we saw if can round in the wrong direction.  With the decimal module, we will be capable of more precise numbers with a little bit more work.


Importing The Decimal Module


We have seen how to import a few modules in previous tutorials, in this tutorial we are going to follow the same steps. To make the decimal module to work we first need to import the module and we do this by entering the following “import decimal” with no quotes.  Once we have imported the Python decimal module we will be able to access the functions included in the module.


Importing The Decimal Module Example


#import the whole module. We will use this method in this tutorial

>>> import decimal

#import a specific function in the module
>>> from decimal import Decimal

In this Python decimal module, tutorial we will just use import decimal. This will make it easier to focus on the decimal module over importing specific functions.


Working With Python Decimal Module


First we need to look at an example where we would need to use the decimal module. Let’s look at the example we have been using over and over in our last two tutorials.


Why We Need Decimal Module Example


#below you will find two examples why we would need to use the decimal module

#answer should be 16.3
>>> 7.6 + 8.7
16.299999999999997

Ways To Fix This Using the Decimal Module


Method 1


In this example, we set a global precision on our decimal module and we may be limited in using this method. Take a look at how it works.


#first example

#issue
>>> 7.6 + 8.7
16.299999999999997

#import Decimal Module
>>> import decimal

#set the precision globally this tells decimal module we want 3 numbers returned.
>>> decimal.getcontext().prec = 3

#Now add the two numbers together using the decimal module
>>> decimal.Decimal(7.6) + decimal.Decimal(8.7)
Decimal('16.3')

In the above example, we take our problem floating point number and we use the decimal module to return the correct number. Let’s take a closer look at the process we use above.


Import Decimal Module


First we import the Python decimal module.  This needs to be done so we can use the functions the module contains.


Code: import decimal


Set Global Precision


When we set global precision the program to only show three numbers with our code.  Global means that our program will only show three numbers throughout our program or until we change it. This method may not be the best if you are working with numerous different numbers.


Code: decimal.getcontext().prec = 3


The Equation


Here we perform a simple addition equation.  We do have some words in front of our floats.  The first word decimal says go to the module decimal and then the second word Decimal says get the Decimal function which is inside the decimal module.


Code: decimal.Decimal(7.6) + decimal.Decimal(8.7)


Method 2


In this example, we will set the precision for our numbers temporarily so we will look at global with temporary precision adjustment.


#Temporary Precision

#import decimal module
>>> import decimal

#set global
>>> decimal.getcontext().prec = 3

#our equation for this example but we want the dollar and cents in this equation. We only get 3 numbers which are the dollars
>>> decimal.Decimal(78.96) + decimal.Decimal(90.99)
Decimal('170')

#temporary fix setting our precision for one equation
>>> with decimal.localcontext() as ctx:
... ctx.prec = 5
... decimal.Decimal(78.96) + decimal.Decimal(90.99)
...
Decimal('169.95')

#see only temporary
>>> decimal.Decimal(78.96) + decimal.Decimal(90.99)
Decimal('170')

Import Decimal Module


Is the same as above example


code: import decimal


Set Global Precision


Is the same as above example


Code: decimal.getcontext().prec = 3


The Equation


Here we have an equation and in this equation we want to find out how much a client owes you. This equation does not show cents and rounds up so your client is paying you more than is actually owed to you. This may not be the best choice when running a business


code: decimal.Decimal(78.96) + decimal.Decimal(90.99)


The Temporary Precision Solution


What in the world is that funky looking code. We are nowhere near learning about exceptions in Python but I thought I would share this one to show you the possibilities in Python and the decimal module. Let’s take a closer look “With” is an exception statement in Python. So, what I did here was say “with” the “decimal module” look inside the decimal module and get the “localcontext()” function and set this function “as” a variable called “cxt” so we can call it in the statement. The next line you must indent in your Python interpreter(I use two spaces) we set the precision using “cxt” variable like this cxt.precision = 5. After, we define the precision we can run our equation like before. Then in Python interpreter press return twice.


This also may not be the best solution for your program seems like a lot of code to do something simple.


Method 3


This is our final example in this tutorial. If you are looking for more precise decimal numbers then quantize may be our best option. We use quantize to return the exact amount of decimal numbers.


#using quantize in decimal module

#import decimal
>>> import decimal

#assign a variable an equation
>>> a = decimal.Decimal(78.96 * 89.65)

#Then use quantize to set exact decimal position
>>> a.quantize(decimal.Decimal('0.00'))
Decimal('7078.76')

Import Decimal Module


Same as before


code: import decimal


A Variable assigned To An Equation


Here we allocate a variable to an equation. We use a variable to cut down on the amount of code we need to type, but we could have done it all on one line. This is just simpler.  So with equation, we want to know the monetized amount so we want two numbers after the decimal point.


Quantize The Decimal


Here we use a method to round the number to a certain set of numbers after the decimal. We use a method called quantize to achieve this. We set how we want the method to return the value with ‘0.00’ it must be in a string format. If we want more numbers after the decimal for example we want four we could do ‘0.0000’ to make this happen.


Last Example


We also looked at another problem using the built-in function round().  round(2.675, 2) this function does not round as we expect so is there a way to fix this?  Of course there is. 


#Last Example Fixing Rounding Issues

#This should round up to 2.68
>>> round(2.675, 2)
2.67

#Lets take a look at what this number actually represents
>>> b = decimal.Decimal(2.675)
>>> b
Decimal('2.67499999999999982236431605997495353221893310546875')

#as you can see it rounds down because of the 4 instead of the five

#the fix
b.quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)
Decimal('2.68')

In this example we once again use the quantize module but this time we use rounding to tell Python to round the number up.  We can use the following rounding commands ROUND_CEILING, ROUND_UP, ROUND_HALF_UP, ROUND_FLOOR, ROUND_DOWN, ROUND_05UP, ROUND_HALF_EVEN.


In Conclusion


We have taken a brief look at the Python decimal module. This is not a full tutorial on this module and we do have one planned for the future.  That tutorial will need to be broken down into several mini tutorials do the shear size of the Python decimal module. If you want to read more about the Python decimal module visit https://docs.python.org/3.4/library/decimal.html#module-decimal If you have any questions about today’s tutorial, please leave a comment below.



Sunday, May 3, 2015

Garbage Collection - Python Tutorial



Garbage collection is the way Python manages memory in a program.  This method is automatic or we have an option to control the garbage collection through a module called garbage collection(gc).

Check out our tutorial on garbage collection at Garbage Collection


View video tutorial on Youtube at https://youtu.be/hg01TTzi6Xk


Tutorial on garbage collection module coming soon!



round() Built-in Function In Python - Python Numbers - Python Tutorial

round() built-in function in Pythonround() Built-in Function In Python


In our previous Python tutorial, we looked at some weird numbers you can get when you doing math with floating point numbers in Python. We also explained that this is not some bug that it has to do with the underlying c language and how it handles floating point numbers. C language converts floating point numbers to fractions and when those fractions are called by Python they again are converted to float and the conversion between a float and fraction are not always accurate.

We also discussed that one of the ways around this minor issue is using a built-in function in Python called round(). Round() will round the floating point number to a certain number to the right of the decimal which we can control in the syntax. To get started with round() let’s look at the syntax for the round() built-in function in Python.


round() Syntax


round(First Argument, Second Argument)


First Argument


This is where we input the float that we want to round.


Second Argument


The second argument is after the comma. This location is where we can declare how many numbers after the decimal we want to use. If we give no second argument then the argument defaults to zero.


round() Examples


#Round Examples

#From the previous tutorial
>>> 7.6 + 8.7
16.299999999999997

#How to fix the above example
>>> round(7.6 + 8.7, 1)
16.3

#Another example
>>> a = 0.1 + 0.2
>>> a
0.30000000000000004
>>> round(a,1)
0.3

#How about more numbers after the decimal
>>> b = 9.5434 * 983245.8943
>>> b
9383508.86766262
>>> round(b, 4)
9383508.8677

Well that is pretty easy use and fix the occasional inaccuracy in Python numbers. Well the round() built-in function in Python does have its own issues.  Take a look at this example.


Round() Issues


#Round() Issues

#This doesn't make sense
>>> round(2.675, 2)
2.67

#Now you are probably even more confused
>>> round(8.875, 2)
8.88

Well now that we confused you a bit this comes back to the previous tutorial where the underlying c language and how it converts floats to fractions and back again. Not every float can be displayed properly. In this tutorial, we saw where round() could help and we also saw where round() could hurt a bit.We will look at the decimal module in the next tutorial and see how that can help us work together with floats.

In this tutorial, we saw how the round() built-in function could help us in most situations but there are times when round() built-in function in Python may not be the best choice. We will look at our other option in the next tutorial. If you have any questions about round() leave a comment below and we will help you.


 



Saturday, May 2, 2015

Why are floating point calculations so inaccurate? - Python Numbers - Python Tutorial

Why are floating point calculations so inaccurateWhy are floating point calculations so inaccurate?


This may be deeper than you are ready to go at this point in learning Python but it is important to understand that floating point numbers may not be returned as you expect with performing calculations in Python. To kick off this tutorial let’s take a look at an example of this weird problem you may come across in Python.


Example of Floating Point Calculations


#Example of Floating Point Calculations

>>> 7.6 + 8.7
16.299999999999997

7.6 + 8.7 should equal 16.3 correct?  Why does Python have this bug?  It is not a bug actually. This is related to the underlying c language which Python is built on. This issue can seen in a lot of computer programming languages not just in Python.


Why Does This Happen?


This happens when the c language attempts to represent floating point numbers. C language uses binary numbers to account for floating point numbers but these numbers sometimes return numbers with a small round off error. Floating point numbers are actually handled as fractions then converted to floating point numbers when displayed. The conversion from a fraction to a floating point number is not so accurate as you may like.


How Can I Make My Floating Point Numbers More Accurate?


We have two options.  We could use round() which is a built-in function or we could use the decimal module. We will cover the built-in round() function in the next tutorial and then the following tutorial we will cover the decimal module. We will see how to work around this issue within Python.


In conclusion


We saw how floating point numbers are represented in Python and that it is not an issue with Python but an issue with how the underlying c language represents floating point numbers. We now know that floating point numbers are broken down into fractions and then returned to us as floating point numbers where fractions are not as accurate as floating point numbers. This will give us a slight rounding issue with our floating point numbers.  There are ways to be more exact by either using a built-in function called round or by using a module called decimal. Now that you understand that Why are floating point calculations so inaccurate in Python we can safely say we are moving in the right direction to learn programming.



gc.get_threshold() - Python Tutorial


gc.get_threshold()


gc.get_threshold() is a function that we can use when we import the garbage collection module. This function will return when the garbage collection algorithm will run to clean up the memory. The number that is returned to us is the threshold when the algorithm is ran.  


gc.get_threshold() Example


#gc.get_threshold()

>>> import gc
>>> gc.get_threshold()
(700, 10, 10)

 


gc.get_threshold(threshold0, threshold1, threshold2)


You will see three numbers returned to us and these numbers are set at three different runs of the garbage collection. First one is ran when the allocations minus the deallocations exceed the number displayed.Default for threshold0 is 700. If the object survives the first run it is relocated into the second run. The second number returned to us is when the second garbage collection will run this is threshold1 of garbage collection this number is based on the number runs that threshold0 does. The succeeding generation default is 10 so in this case threshold0 run must run ten times before the threshold1 of garbage collection is ran. If an object survives the subsequent run it is now moved into the third and final run and the object will stay here until it is removed. Threshold2 will run based off threshold1 runs.  The default is 10 threshold1 runs. So, when the threshold1 runs ten times the final generation will run.


 



Friday, May 1, 2015

Python Numbers - Chapter 4 - Python Tutorial

Python NumbersPython Numbers


Welcome to Python Numbers in chapter 4 of our Python Tutorials we are going to focus on numbers, math that we can perform in Python, operators used for numbers, a couple math modules and booleans.  Like the previous chapter, we will go deep into the Python numbers and focus on each and every aspect of Python numbers.


Python Numbers Tutorials


Below you will find a list of the scheduled Python numbers tutorials. These tutorials are not set in stone and can change as we move along.


  1. Why are floating point calculations so inaccurate?

  2. Round() Built-in Function

  3. Python Decimal Module

  4. Python Addition

  5. Python Subtraction

  6. Python Multiplication

  7. Python Division

  8. Python Modulo

  9. Python Exponentiation

  10. Python Mixed Operators Flow

  11. Manually Adjust The Operator Precedence

  12. Convert Number Types in Python

  13. Booleans In Python

  14. Python Comparison Operators

  15. Python Sets

  16. Python Booleans

  17. Python Math Module

 


 



Python Garbage Collection - Python Variables - Python Tutorial

 


Python Garbage CollectionPython Garbage Collection


One of the nicest things about the Python programming language is the Python garbage collection feature which will monitor and free up memory automatically. If we had to manage memory in Python programs we would devote more time allocating memory in our programs then we would be writing the program. In this Python tutorial, we will have a close look at how Python manages memory with its garbage collection algorithm.


What is Garbage Collection?


Garbage collection is a process whereby a program runs some code to clean up unused memory. In previous Python tutorials, we have discussed that the blocks of memory in Python are designated as objects. When these objects are not required anymore than the garbage collection system jumps in and removes those objects to clear up memory for more objects. This is all automatic so we are not required to initiate the garbage collection system to free up memory.


How Does The Garbage Collection Work?


When an object is no longer used then the garbage collection algorithm will remove the object. This is where the reference counter becomes involved. If the object is referenced then the reference counter increments up by one and when the reference to that object is removed then the counter increments down.  When the objects reference counter is at zero(No References To The Object) then that object will be deleted. The reference counter method is great but there are cases where this method of removing objects doesn’t always work.


Reference Cycles


Sometimes the objects reference counter never goes to zero and there is a lack of physical reference to an object. This happens when an object reference itself and this is referred to as a reference cycle. In this case, Python relies on a schedule for garbage collection to run. Each time a reference is added or removed the system will count the occurrence and when the number of occurrences reaches a set number then the garbage collection will run and remove reference cycles.


#Example of a Reference Cycle

>>> a = []
>>> a.append(a)
>>> a
[[...]]

In the above example, the variable “a” is assigned to an empty list then we append “a” to itself. Now we have an object referencing itself and in this case the list objects reference counter would never go to zero.


When Will Garbage Collection Run?


Garbage collection runs when the number of references added and deleted hit a certain number. We can find this number by importing the garbage collection module which gives us the ability to control the garbage collection. Let’s take a look at when will the garbage collection runs.


#When Will Garbage Collection Run?

>>> import gc
>>> gc.get_threshold()
(700, 10, 10)

We see 700 that means deallocation must reach 700 then the garbage collector will run and remove reference cycles. If an object is not removed in the first run it is forwarded to the second run. The second run will run when first run has run 10 times. If an object survives it will be moved to the third run which is the definitive run and this where the object will stay till it is removed. The third run will run when the second run has run ten times.


Now we have covered the Python Garbage Collection we understand how Python automatically handles memory.  There is a module called garbage collection which we briefly discussed in this tutorial. We will examine the garbage collection module in full in its own tutorial. If you have any questions please let us know by leaving a comment below.


Updated


March 11, 2015 – Changed the explanation of garbage collection run times