Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Python Programming/Numbers

From Wikibooks, open books for an open world
<Python Programming
Previous: Data typesIndexNext: Strings


Python 2.x supports 4 built-in numeric types - int, long, float and complex. Of these, the long type has been dropped in Python 3.x - the int type is now of unlimited length by default. You don’t have to specify what type of variable you want; Python does that automatically.

  • Int: The basic integer type in python, equivalent to the hardware 'c long' for the platform you are using in Python 2.x, unlimited in length in Python 3.x.
  • Long: Integer type with unlimited length. In python 2.2 and later, Ints are automatically turned into long ints when they overflow. Dropped since Python 3.0, use int type instead.
  • Float: This is a binary floating point number. Longs and Ints are automatically converted to floats when a float is used in an expression, and with the true-division/ operator. In CPython, floats are usually implemented using the C languagesdouble, which often yields 52 bits of significand, 11 bits of exponent, and 1 sign bit, but this is machine dependent.
  • Complex: This is a complex number consisting of two floats. Complex literals are written as a + bj where a and b are floating-point numbers denoting the real and imaginary parts respectively.

In general, the number types are automatically 'up cast' in the following order:

Int → Long → Float → Complex. The farther to the right you go, the higher the precedence.

>>>x=5>>>type(x)<type'int'>>>>x=187687654564658970978909869576453>>>type(x)<type'long'>>>>x=1.34763>>>type(x)<type'float'>>>>x=5+2j>>>type(x)<type'complex'>

The result of divisions is somewhat confusing. In Python 2.x, using the / operator on two integers will return another integer, using floor division. For example,5/2 will give you 2. At least one of the operands must be float to get true division, e.g.5/2. or5./2 (the dot makes a number a float) will yield 2.5. Starting with Python 2.2 this behavior can be changed to true division by the future division statementfrom __future__ import division. In Python 3.x, the result of using the / operator is always true division (you can ask for floor division explicitly by using the // operator since Python 2.2).

This illustrates the behavior of the / operator in Python 2.2+:

>>>5/22>>>5/2.2.5>>>5./22.5>>>from__future__importdivision>>>5/22.5>>>5//22

For operations on numbers, see chaptersBasic Math andMath.

Links

[edit |edit source]
Previous: Data typesIndexNext: Strings
Retrieved from "https://en.wikibooks.org/w/index.php?title=Python_Programming/Numbers&oldid=4394402"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp