Monday, March 19, 2012

csci133number.py

Reference: http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex
Please, please, please click on it and read it if you want to know the full details of the information. The reference page tell you exactly everything you ever need to understand them!

There are total of 4 number type (or Numeric Type): integers, float, long, complex.
  • Integer - implemented using long in C, have 32bits of precisions.  Integers can be positive and negative, but they are whole numbers. (1,2, 3, 4, 5, 0, -1, -2..)
  • Floating point - implemented using double in C. When you need decimal point, you can use floating point. Such as 1234.5 + 1234.5.
  • Long integers - have unlimited amount of precisions. (See here for long integers). It is useful if you are calculating the amount of debt United States is under. (wink wink)
  • Complex - have real and imaginary component to it. (See here for Complex numbers). I think it is very useful, but I am not yet familiar with it yet, I shall come back to it soon.
If floating point is not enough for your usage, you can also use fraction, and decimal. Python is very nice because it support mixed arithmetic, when you do this, python will convert the broader type into narrower type. For example: Integer * Floating point = Integer.

The relationship is the follow: Complex > Floating point > Long Integer > Integer
# Get the absolute value 
abs(-5)

# Convert something into integer
myNumberInString = '100'
anotherNumber = 50
result = 0
result += int(myNumberInString) + anotherNumber

# The power of x function 2^3
pow(2, 3)

There is a thing called module, it is a package of tools. Similar to header files in C++, remember the math class in C++? There is one similar to it in python, and it is called math too. We have to always import the module before we can use its tool. There are many of them, feel free to experiment with it, they provide you a lot of useful subroutine.
# Sample code for math moduele
import math
print(math.pi)
>>> 3.1415926535897931

No comments:

Post a Comment