CSC1015_Slides03_Michelle_PythonNumbers_2013 OA

Download Report

Transcript CSC1015_Slides03_Michelle_PythonNumbers_2013 OA

CSC1015F – Chapter 3, Computing
with Numbers
Michelle Kuttel
[email protected]
Data Types

Data can have many different types

Python is dynamically typed

In a dynamically typed language, a variable is simply a value
bound to a name;
the value has a type -- like "integer" or "string" or "list" -- but the
variable itself doesn't.
x=“hello”
x=2.5

In a statically typed language, the variable itself has a type


2
if you have a variable that's an integer, you won't be able to assign any
other type of value to it later.
The type function
Tells you what type (or “class”) your data item is. e.g.:

>>> type(3)
<type ’int’>
>>> type(3.14)
<type ’float’>
>>>type(3+2.1j)
<class 'complex'>
3
The type function
Tells you what type (or “class”) your data item is. e.g.:

>>> myInt = -32
>>> type(myInt)
<type ’int’>
>>> myFloat = 32.0
>>> type(myFloat)
<type ’float’>
4
Numeric Data Types
For numbers we have two BASIC types:
 integers:

whole numbers with no fractional part
floating point number:





5
numbers with fractional part
WARNING: store only an approximation to real numbers
there is a limit to the precision, or accuracy, or the stored
values
e.g. 10/3
Checkpoint: Why are there two basic
types for numbers?
6
Checkpoint: Why are there two basic
types for numbers?
style:


an integer can’t be a floating point
efficiency:



7
integer arithmetic is simpler, and therefore faster, than for
floating point numbers.
If you don’t need a float, use an int
Numeric Data Types
We also have:
 Complex numbers




8
combination of real and imaginary components
Both represented by floating-point numbers
imaginary part denoted by ‘j’
e.g. 3+2.1j
Python built-in numeric operators
+
*
/
**
%
abs()
//
9
addition
subtraction
multiplication
float division
exponentiation
remainder
absolute value
integer division
Numeric operations
For the most part, operations on floats produce floats and
operations on integers produce integers

e.g. ….
However, division is a bit more interesting.
 the / operator ALWAYS returns a float
because dividing two ints can produce a float
10
Numeric operations
For the most part, operations on floats produce floats and
operations on integers produce integers

e.g. ….
However, division is a bit more interesting.
 the / operator ALWAYS returns a float
because dividing two ints can produce a float
WHY IS THIS A GOOD IDEA?
11
Why is this a good idea?

Many computer languages, including Fortran, C, C++, and
Java (and Python pre version 3), interpret a division
operation a/b as integer division, if both operands a
and b are integers.


This confusion leads to one of the most common errors
in mathematical software


ONLY IF either a or b is a real (floating-point) number,
DOES a/b implies the standard mathematical float division.
not at all obvious for a newcomer to programming.
Python 3 fixes this!
12
Example: Temperature converter
# convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Suzie Programmer
def main():
celsius = eval(input("What is the Celsius temperature?
"))
fahrenheit = 9/ 5 * celsius + 32
print "The temperature is", fahrenheit, "degrees
Fahrenheit.”
main()
13
Numeric operations

to ensure an integer result, use //
 truncating division operator
 also known as floor division

examples….
14
Checkpoint
In Python 3, the expression 10//3 will evaluate as:
a.
b.
c.
d.
15
3.3333333333333333
3.3333333333333335
3
3.0
Checkpoint
In Python 3, the expression 10/3 will evaluate as:
a.
b.
c.
d.
16
3.3333333333333333
3.3333333333333335
3
3.0
Checkpoint
In Python 3, the expression '10.0'*2 will evaluate as:
a.
b.
c.
d.
17
20
20.0
'10.010.0'
Syntax error
Checkpoint
In Python 3, the expression -7//3 will evaluate as:
a.
b.
c.
d.
18
-2
-3
-2.3333333333333335
-2.3333333333333333
NOTE: Integer division of negative
numbers


Python (and Ruby) define integer division of or by a
negative number differently to C and Java.
e.g. -7//3


Java = -2
Python= -3
integer arithmetic is not as simple as it appears!
19
Checkpoint
In Python 3, the expression 8//3*2.0 will evaluate as:
1.
2.
3.
4.
20
5.333333333333333
10
4
4.0
Type Conversions




We know that combining an int with an int produces an
int,
and combining a float with a float produces a float.
What happens when you mix an int and float in an
expression?
x = 5.0 + 2
What do you think should happen?
21
Python Programming, 2/e
Type Conversions

For Python to evaluate this expression, it must either
convert 5.0 to 5 and do an integer addition, or convert 2
to 2.0 and do a floating point addition.

Converting a float to an int will lose information
Ints can be converted to floats by adding “.0”

22
Python Programming, 2/e
Explicit Type Conversion

In mixed-typed expressions Python will convert ints to
floats.

Sometimes we want to control the type conversion. This
is called explicit typing.
23
Python Programming, 2/e
Type Conversions
>>> float(22//5)
4.0
>>> int(4.5)
4
>>> int(3.9)
3
>>> round(3.9)
4
>>> round(3)
3
24
Python Programming, 2/e
Checkpoint: Explain in English what
this program does
number = eval(input("Type in a number:\n") )
divisor = eval(input("What do you want to divide by?"))
intResult = number//divisor
remainder = number%divisor
print(number,"/", divisor, "=", intResult, "remainder",
remainder)
25
Math library


Python provides many other useful mathematical
functions in a special math library.
A library is just a module that contains some useful definitions
26
Math library
The math functions operate on integers and floats but do
not work with complex numbers (a separate module –
cmath - can be used to perform similar operations on
complex numbers).


The return value of all functions is a float.
All trigonometric functions assume the use of radians.
27
Math library
sin(x) Returns the sine of x.
cos(x) Returns the cosine of x.
tan(x) Returns the tangent of x.
acos(x) Returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
degrees(x) Converts x from radians to degrees.
radians(x) Converts x from degrees to radians.
28
Math library
exp(x) Returns e ** x.
ceil(x) Returns the ceiling of x.
floor(x) Returns the floor of x.
copysign(x,y) Returns x with the same sign as y.
fabs(x) Returns the absolute value of x.
factorial(x) Returns xfactorial.
hypot(x, y) Returns the Euclidean distance,sqrt(x* x+
y* y).
isinf(x) Return True if x is infinity.
29
Math library
isnan(x) Returns True if x is NaN.
ldexp(x, i) Returns x* (2 ** i).
log(x[, base]) Returns the logarithm of x to the
given base. If base is omitted, this function computes the
natural logarithm.
log10(x) Returns the base 10 logarithm of x.
pow(x, y) Returns x** y.
sqrt(x) Returns the square root of x.
trunc(x) Truncates x to the nearest integer towards 0.
30
Using the Math Library
In the textbook:
 writing a program to compute the roots of a quadratic
equation:
b  b2  4ac
x
2a

The only part of this we don’t know how to do is find a
square root… but it’s in the math library.
31
Python Programming, 2/e
Using the Math Library

To use a library, we need to make sure this line is in our
program:
import math

Importing a library makes whatever functions are defined
within it available to the program.
32
Python Programming, 2/e
Using the Math Library

To access the sqrt library routine, we need to access it as
math.sqrt(x)

Using this dot notation tells Python to use the sqrt
function found in the math library module.

To calculate the root, you can do
discRoot = math.sqrt(b*b – 4*a*c)
33
Python Programming, 2/e
Math Library

Using the sqrt function is more efficient than using **.
How could you use ** to calculate a square root?
The Limits of Int






>>> import math
>>> math.factorial(100)
93326215443944152681699238856266700490715968264
38162146859296389521759999322991560894146397615
65182862536979208272237582511852109168640000000
00000000000000000
>>>
Wow! That’s a pretty big number!
And Python can handle it….. can Java?
35
Python Programming, 2/e
The Limits of Int

What’s going on?



36
While there are an infinite number of integers, there is a finite
range of ints that can be represented.
This range depends on the number of bits a particular CPU
uses to represent an integer value.
Typical PCs use 32 bits.
Python Programming, 2/e
The Limits of Int

Typical PCs use 32 bits



That means there are 232 possible values, centered at 0.
This range then is –231 to 231-1. We need to subtract one
from the top end to account for 0.
In 32-bit, the largest number that can be stored is

37
2147483647
Python Programming, 2/e
The Limits of Int

Can use floats, but then no longer get an exact answer




float(math.factorial(100))
9.332621544394415e+157
lost after the 16th digit!
float are approximations – the precision is fixed, larger range
But 100! was fine ?
 how does it work in Python?
38
Python Programming, 2/e
Handling Large Numbers: Long Int



Very large and very small numbers are expressed in
scientific or exponential notation.
1.307674368e+012 means 1.307674368 * 1012
Here the decimal needs to be moved right 12 decimal
places to get the original number, but there are only 9
digits, so 3 digits of precision have been lost.
39
Python Programming, 2/e
Handling Large Numbers

Python has a solution, expanding ints!

Python ints are not a fixed size and expand to handle
whatever value it holds.
40
Python Programming, 2/e
Handling Large Numbers

Newer versions of Python automatically convert your
ints to expanded form when they grow so large as to
overflow.

to do mathematical operations, Python breakers the
expanded int into smaller pieces

We get indefinitely large values (e.g. 100!) at the
cost of speed and memory

41
There is NO free lunch (ever)!!
Python Programming, 2/e
More about libraries: random library
Pseudo-random numbers
import random

randint(a,b)

Returns a random integer, x, in the range a <= x <= b.
random()

Returns a random number in the range [0.0, 1.0).
42
Example program: Kiddymaths2
import random
#do this to use functions in random
def test():
start,stop=1,10
start2,stop2=1,10
dividend = random.randint(start,stop)
divisor = random.randint(start2,stop2)
intResult = dividend // divisor
remainder = dividend % divisor
print(dividend,"/", divisor, "=", intResult,
"remainder", remainder)
test()
43
Improving “Kiddymaths”
How do we ask the children for the answer and check
whether they are correct?
 Need SELECTION statements…
44

This work is licensed under a Creative Commons
Attribution-ShareAlike 2.5 South Africa License.
45