官术网_书友最值得收藏!

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\times10^{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.

主站蜘蛛池模板: 新绛县| 随州市| 全州县| 恩平市| 体育| 东平县| 西乡县| 辽宁省| 彭州市| 荃湾区| 浦江县| 黔西县| 磐石市| 柳州市| 临高县| 冕宁县| 改则县| 广昌县| 丹阳市| 东至县| 崇义县| 文山县| 蓬安县| 衡南县| 东乌珠穆沁旗| 苍南县| 延吉市| 寿阳县| 西乌珠穆沁旗| 临邑县| 新疆| 静安区| 密山市| 兴仁县| 莎车县| 泉州市| 景泰县| 泰和县| 随州市| 乐业县| 邯郸市|