** Basic math
:PROPERTIES:
:categories: python, math
:date: 2013/02/27 07:35:24
:updated: 2013/02/27 14:49:05
:END:
Python is a basic calculator out of the box. Here we consider the most basic mathematical operations: addition, subtraction, multiplication, division and exponenetiation. we use the func:print to get the output. For now we consider integers and float numbers. An integer is a plain number like 0, 10 or -2345. A float number has a decimal in it. The following are all floats: 1.0, -9., and 3.56. Note the trailing zero is not required, although it is good style.
#+BEGIN_SRC python
print 2 + 4
print 8.1 - 5
#+END_SRC
#+RESULTS:
: 6
: 3.1
Multiplication is equally straightforward.
#+BEGIN_SRC python
print 5 * 4
print 3.1*2
#+END_SRC
#+RESULTS:
: 20
: 6.2
Division is almost as straightforward, but we have to remember that integer division is not the same as float division. Let us consider float division first.
#+BEGIN_SRC python
print 4.0 / 2.0
print 1.0/3.1
#+END_SRC
#+RESULTS:
: 2.0
: 0.322580645161
Now, consider the integer versions:
#+BEGIN_SRC python
print 4 / 2
print 1/3
#+END_SRC
#+RESULTS:
: 2
: 0
The first result is probably what you expected, but the second may come as a surprise. In integer division the remainder is discarded, and the result is an integer.
Exponentiation is also a basic math operation that python supports directly.
#+BEGIN_SRC python
print 3.**2
print 3**2
print 2**0.5
#+END_SRC
#+RESULTS:
: 9.0
: 9
: 1.41421356237
Other types of mathematical operations require us to import functionality from python libraries. We consider those in the next section.