Different types of numbers

Remember that when we used factorial() alone it returned an integer. But our
more complex expression above for calculating combinations is producing a floating point number. This is because we've used /, Python's floating-point division operator. Since we know our operation will only ever return integral results, we can improve our expression by using //, Python’s integer division operator:

>>> from math import factorial as fac
>>> fac(n) // (fac(k) * fac(n - k))
10

What's notable is that many other programming languages would fail on the above expression for even moderate values of n. In most programming languages, regular garden variety signed integers can only store values less than {ParseError: KaTeX parse error: Expected 'EOF', got '}' at position 1: }̲2 imes10^{31}}:

>>> 2**31 - 1
2147483647

However, factorials grow so fast that the largest factorial you can fit into a 32-bit signed integer is 12! since 13! is too large:

>>> fac(13)
6227020800

In most widely used programming languages you would need either more complex code or more sophisticated mathematics merely to compute how many ways there are to draw 3 fruits from a set of 13!. Python encounters no such problems and can compute with arbitrarily large integers, limited only by the memory in your computer. To demonstrate this further, let's try the larger problem of computing how many different pairs of fruit we can pick from 100 different fruits (assuming we can lay our hands on so many fruit!):

>>> n = 100
>>> k = 2
>>> fac(n) // (fac(k) * fac(n - k))
4950

Just to emphasize how large the size of the first term of that expression is, calculate 100! on it's own:

>>> fac(n)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

This number is vastly larger even than the number of atoms in the known universe, with an awful lot of digits. If, like us, you're curious to know exactly how many digits, we can convert our integer to a text string and count the number of characters in it like this:

>>> len(str(fac(n)))
158

That's definitely a lot of digits. And a lot of fruit. It also starts to show how Python's different data types — in this case, integers, floating point numbers, and text strings — work together in natural ways. In the next section we'll build on this experience and look at integers, strings, and other built-in types in more detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset