CSC1015F – Chapter 3, Computing with Numbers Michelle Kuttel

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

Return values.
2009 Spring Errors & Source of Errors SpringBIL108E Errors in Computing Several causes for malfunction in computer systems. –Hardware fails –Critical.
Types and Arithmetic Operators
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Numbers. Number data types store numeric values They are immutable data types, which means that changing the value of a number data type results in a.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Python Programming: An Introduction to Computer Science
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Representation and Conversion of Numeric Types 4 We have seen multiple data types that C provides for numbers: int and double 4 What differences are there.
Chapter 3 Computing with Numbers
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e1.
CSC 110 Numeric data types [Reading: chapter 3] CSC 110 D 1.
Vahé Karamian Python Programming CS-110 CHAPTER 3 Computing with Numbers.
CS0004: Introduction to Programming Variables – Numbers.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
Computer Organization and Architecture Computer Arithmetic Chapter 9.
Fall, 2006Introduction to FORTRAN1 (2 + 2 = ???) Numbers, Arithmetic Nathan Friedman Fall, 2006.
Chapter 3.  Traditionally, programming languages have assigned different types of data for different types of numbers.  In many languages, there may.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Input, Output, and Processing
CSC Programming I Lecture 5 August 30, 2002.
CSC 221 Computer Organization and Assembly Language
Math With Java The Math Class. First, A Quick Review of Math Operators in Java Primitive Data type in Java that represent numbers: Primitive Data type.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Copyright © – Curt Hill Types What they do.
CS1Q Computer Systems Lecture 2 Simon Gay. Lecture 2CS1Q Computer Systems - Simon Gay2 Binary Numbers We’ll look at some details of the representation.
Computer Graphics Basic Maths for Graphics in C++ CO2409 Computer Graphics Week 4.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Programming Languages Programming languages are a compromise between spoken language and formal math. They allow humans to communicate with computers at.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Primitive Data Types. int This is the type you are familiar with and have been using Stores an integer value (whole number) between -2,147,483,648 (-2.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
Python Programming, 3/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Floating Point Representations
Variables, Operators, and Expressions
Simple C Programs.
Today Variable declaration Mathematical Operators Input and Output Lab
Python Programming: An Introduction to Computer Science
Computer Graphics Basic Maths for Graphics in C++
BIL 104E Introduction to Scientific and Engineering Computing
TMF1414 Introduction to Programming
CSC 131: Introduction to Computer Science
Multiple variables can be created in one declaration
Modified from Sharon Guffy
Introduction to Programming
Arithmetic Operator Operation Example + addition x + y
Building Java Programs
Arithmetic Expressions & Data Conversions
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Building Java Programs Chapter 2
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Building Java Programs
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

CSC1015F – Chapter 3, Computing with Numbers Michelle Kuttel

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  if you have a variable that's an integer, you won't be able to assign any other type of value to it later. 2

The type function  Tells you what type (or “class”) your data item is. e.g.: >>> type(3) >>> type(3.14) >>>type(3+2.1j) 3

The type function  Tells you what type (or “class”) your data item is. e.g.: >>> myInt = -32 >>> type(myInt) >>> myFloat = 32.0 >>> type(myFloat) 4

Numeric Data Types For numbers we have two BASIC types:  integers:  whole numbers with no fractional part  floating point number:  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 5

Checkpoint: Why are there two basic types for numbers? 6

 style:  an integer can’t be a floating point  efficiency:  integer arithmetic is simpler, and therefore faster, than for floating point numbers.  If you don’t need a float, use an int 7

Numeric Data Types We also have:  Complex numbers  combination of real and imaginary components  Both represented by floating-point numbers  imaginary part denoted by ‘j’  e.g j 8

Python built-in numeric operators +addition -subtraction *multiplication /float division **exponentiation %remainder abs()absolute value //integer division 9

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.  ONLY IF either a or b is a real (floating-point) number, DOES a/b implies the standard mathematical float division.  This confusion leads to one of the most common errors in mathematical software  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. 3 d

Checkpoint In Python 3, the expression 10/3 will evaluate as: a b c. 3 d

Checkpoint In Python 3, the expression '10.0'*2 will evaluate as: a. 20 b c. ' ' d. Syntax error 17

Checkpoint In Python 3, the expression -7//3 will evaluate as: a. -2 b. -3 c d

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:

Python Programming, 2/e 21 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 =  What do you think should happen?

Python Programming, 2/e 22 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 ”

Python Programming, 2/e 23 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.

Python Programming, 2/e 24 Type Conversions >>> float(22//5) 4.0 >>> int(4.5) 4 >>> int(3.9) 3 >>> round(3.9) 4 >>> round(3) 3

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

Python Programming, 2/e 31 Using the Math Library In the textbook:  writing a program to compute the roots of a quadratic equation:  The only part of this we don ’ t know how to do is find a square root … but it ’ s in the math library.

Python Programming, 2/e 32 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.

Python Programming, 2/e 33 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)

Math Library  Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root?

Python Programming, 2/e 35 The Limits of Int  >>> import math  >>> math.factorial(100)   >>>  Wow! That ’ s a pretty big number!  And Python can handle it….. can Java?

Python Programming, 2/e 36 The Limits of Int  What ’ s going on?  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 37 The Limits of Int  Typical PCs use 32 bits  That means there are 2 32 possible values, centered at 0.  This range then is – 2 31 to We need to subtract one from the top end to account for 0.  In 32-bit, the largest number that can be stored is 

Python Programming, 2/e 38 The Limits of Int  Can use floats, but then no longer get an exact answer  float(math.factorial(100))  e+157  lost after the 16 th digit!  float are approximations – the precision is fixed, larger range But 100! was fine ?  how does it work in Python?

Python Programming, 2/e 39 Handling Large Numbers: Long Int  Very large and very small numbers are expressed in scientific or exponential notation.  e+012 means *  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.

Python Programming, 2/e 40 Handling Large Numbers  Python has a solution, expanding ints!  Python ints are not a fixed size and expand to handle whatever value it holds.

Python Programming, 2/e 41 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  There is NO free lunch (ever)!!

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