p { display: inline; } .uk-article br:last-of-type { line-height: 40px; } .slide-page { background: url(/cloud/images/backgrounds/7.jpg) center center no-repeat; background-size: cover; }

Presentation is loading. Please wait.

Presentation is loading. Please wait.

COSC 1306—COMPUTER SCIENCE AND PROGRAMMING FLOATING-POINT NUMBERS Jehan-François Pâris

Similar presentations


Presentation on theme: "COSC 1306—COMPUTER SCIENCE AND PROGRAMMING FLOATING-POINT NUMBERS Jehan-François Pâris"— Presentation transcript:

1 COSC 1306—COMPUTER SCIENCE AND PROGRAMMING FLOATING-POINT NUMBERS Jehan-François Pâris jfparis@uh.edu

2 Floating point numbers Three main differences with integer numbers –Cannot handle well extremely large or extremely small values – Limited precision Can manipulate trillions of dollars but results are not exact to the cent –Must specify number of decimals

3 Limited precision # precision.py """ floating-point computations can be inaccurate """ alpha = 5E9 delta = 5E-9 beta = alpha + delta gamma = beta - alpha print ('delta = ' + str(delta) + ' but gamma = ' + str(gamma))

4 The output delta = 5e-9 but gamma = 0.0 Why? –Computations are carried out with a limited number of significant bits Result has a limited number of significant digits Be careful when computing very small differences between two numbers

5 Note Limitations on floating point number size and precision are – Hardware dependent – Shared by most programming languages Unlike Python, most programming languages do not support arbitrary-size integers –Python is better

6 Displaying floating point numbers Easiest way to specify number of decimal places is string interpolation – 'Answer is %.nf ' %x does two things It inserts the value of x inside the string It specifies that the string representation of x should have n decimal places

7 Example (I) pi = 3.1415917 print('pi equals %.1f‘ % pi ) print('pi equals %.2f' % pi ) print('pi equals %.3f' % pi ) print('pi equals %.4f' % pi )

8 Example (II) Program prints pi equals 3.1 pi equals 3.14 pi equals 3.142 pi equals 3.1416 Values are nicely rounded

9 Converting o F into o C (I) #F2CF.py """converts fahrenheit degrees into celsius degrees """ fahrenheit =float(input('Enter a temperature in degrees Fahrenheit: ')) celsius = (fahrenheit - 32)*5/9 print('%.1f degrees F equals %.1f degrees C' %(fahrenheit, celsius))

10 Converting o F into o C r (II) Output is Enter a temperature in degrees Fahrenheit: 100 100.0 degrees F equals 37.8 degrees C

11 More about string interpolation Can interpolate –Floating-point numbers in scientific notation >>> c = 300000 >>> print('c = %.3e km/s'% c) c = 3.000e+05 km/s – Integers using %d – Strings using %s

12 Example (I) # interpolate.py """ silly demo """ name = input("What's your name?") nclasses=int(input('How many classes are you taking? ')) print ('%s is taking %d classe(s)' %(name, nclasses))

13 Example (II) Output is: What's your name? Bill How many classes are you taking? 5 Bill is taking 5 classe(s)

14 Using the proper quotes We had to use double quotes (") in name = input("What's your name?") because the string contained an apostrophe (') we could have "escaped" the apostrophe as in name = input('What\'s your name?')

15 More escapes Escape sequenceMeaning \' Apostrophe \" Double quote \\ Backslash \n Newline \r Carriage return ( See page 86)

16 Escaping the percent sign Not required in normal strings >>> print("Use the %.3f format") Use the %.3f format Required when we use string interpolation >>> print("Use %.3f to print %.3f" % 3.1416) Use %.3f to print 3.142

17 Boolean type Two values: –True and False Created as –Result of a comparison: ==, !=, >, >=, <, <= –Conversion using bool (…) function Zero values and anything empty converts into a False Anything else converts into a True value

18 Examples >>> a = 3 >>> b = 5 >>> p = (a < b) >>> q = (b <= a) >>> print("p = " + str(p) + “ and q = " +str(q)) p = True and q = False

19 Boolean operations (I) AND: –True if both operands are true aba and b FFF FTF TFF TTT This is called a truth table

20 Boolean operations (II) OR: –True unless both operands are false aba or b FFF FTT TFT TTT

21 Boolean operations (III) NOT: –True if operand is false anot a FT TF

22 Boolean operations (IV) Equality/Mutual Implication: –True when both operands are equal –Represented by a == sign aba == b FFT FTF TFF TTT

23 Boolean operations (V) Inequality/Exclusive OR (XOR): –True when operands are not equal –Represented by a != sign aba != b FFF FTT TFT TTF

24 Notes XOR is used for –Generating parity bits –Hardware hashing

25 Examples Assuming P is True and q is False >>> p or q True >>> p and q False >>> not p False >>> p != q True

26 Variables and objects Variables point to objects –Integers –Strings –Floating-point numbers

27 What is an object? Short for data object Example: dates –Cannot add two dates but can compute their difference –Can initialize date –Can compute weekday(date) –Special date today() –Multiple ways to convert a date into a string

28 Definition An object is an instance of a specific class on which class-specific operations called methods are defined So if an object is of the type date, we will define –A method to initialize a date –A method pr a function to compute the difference of two dates –…

29 String methods These methods never modify the string they apply to! See pages 90 to 95 of text – Do not memorize them (yet) please! One example – s.capitalize(): capitalizes the first letter of the string and converts all other letters to lower case

30 Examples (I) >>> a = 'bill' >>> a.capitalize() 'Bill' >>> b = 'Bill' >>> b.capitalize() 'Bill'

31 Examples (II) >>> c = 'bILL' >>> c.capitalize() 'Bill' >>> d ='Billy Bob' >>> d.capitalize() 'Billy bob‘

32 Better but not perfect – s.title(): capitalizes the first letter of each word in the string and converts all other letters to lower case as in the title case Defines words in a very crude fashion

33 Examples (I) >>> s = 'biLLy Bob' >>> s.title() 'Billy Bob' >>> s ='jehan-francois' >>> s.title() 'Jehan-Francois' >>> s.title()

34 Examples >>> s = "dean's list" >>> s.title() "Dean'S List" >>> s "dean's list" >>>

35 Dollars into bills revisited (I) # dollars2bills.py """ This program prompts repeatedly for a value in dollars and converts it into its equivalents in twenty, ten, five and one dollar bills. It terminates when the user enters a zero value """

36 Dollars into bills revisited (II) # amount is the dollar amount we enter # ntwentys is number of $20 bills we need # ntens is number of $10 bills we need # nfives is number of $5 bills we need # nones is number of $1 bills we need # outstr is our output string

37 Dollars into bills revisited (III) amount = int(input("Enter an integer amount of dollars: ")) while amount != 0 : outstr = '$' + str(amount) + ' is same as ' ntwentys = amount // 20 if ntwentys != 0 : outstr = outstr + str(ntwentys) + ' $20 bill(s) ' temp = amount % 20 ntens = temp // 10 if ntens != 0 : outstr = outstr + 'and ' + str(ntens) + ' $10 bill(s) '

38 Dollars into bills revisited (IV) temp = temp % 10 nfives = temp // 5 if nfives != 0 : outstr = outstr + 'and ' + str(nfives) + ' $5 bill(s) ' nones = temp % 5 if nones != 0 : outstr = outstr + 'and ' + str(nones) + ' $1 bill(s) ' outstr.replace('as and', 'as') print(outstr) amount = int(input("Enter an integer amount of dollars: ")) print('Goodbye!')

39 Outputs Enter an integer amount of dollars: 20 $20 is same as 1 $20 bill(s) Enter an integer amount of dollars: 7 $7 is same as 1 $5 bill(s) and 2 $1 bill(s) Enter an integer amount of dollars: 35 $35 is same as 1 $20 bill(s) and 1 $10 bill(s) and 1 $5 bill(s) Enter an integer amount of dollars: 0 Goodbye!

40 Useful shorthand Can replace  a = a + … by a += …  b = b – … by b –= …  c = c * … by c *= … Cannot use i++, i --, ++i, --i constructs of C  ++i read as +(+i) = i  --i read as –(–i) Does not work!

41 Examples (I) >>> i=1 >>> i += 1 >>> print(i) 2 >>> i++ SyntaxError: invalid syntax >>> ++i 2

42 Examples (II) In the preceding program we could have written outstr += str(ntwentys) + ' $20 bill(s) ' … outstr += 'and ' + str(ntens) + ' $10 bill(s) ' … outstr += 'and ' + str(nfives) + ' $5 bill(s) ' … outstr += and ' + str(nones) + ' $1 bill(s) '

43 Operator precedence (I) Recall the rules of precedence of arithmetic and algebra From highest to lowest –Exponentiation (**) –Unary + and – –Multiplication, divisions and remainder (*, /,//, %) –Addition and subtraction (+ and -)

44 Operator precedence (II) Python extends these rules to other operators From highest to lowest –All arithmetic operations –All comparison operators (==, !=, <, …) –Boolean not –Boolean and (like multiplication) –Boolean or (like addition)

45 Examples x**2*2 + 4*x is same as ((x**2)*2) +( 4*x) (x + 3)/4 + 2 is same as ( (x + 3)/4) + 2

46 Examples Allows us to write if a < b and c < d : for if (a < b) and (c < d ): Allows us to write a and b or not c for ( a and b ) or (not c)

47 A common sense rule Some expressions such as a*x**2 + b*x + c do not need parentheses Nobody has ever been fired for writing if (a < b) and (c < d ): or even ( a and b ) or (not c) It is always better to play safe!

48 How our programs are translated Our programs are not written in machine language –Cannot be directly executed by any computer –Must be first translated Two approaches –Compiled languages –Interpreted languages

49 Compiled languages (I) Programs written in Fortran, C, C++ and so on go to a program that translates them into directly executable code –The compiler Doing gcc myprogram.c –o myprogram produces an executable file called myprogram that can run anytime

50 Compiled languages (II) C program C compiler Executable

51 Advantages The executable can run on any computer with –Same CPU instruction set –Same—or compatible—operating system We can sell copies of the executable without revealing the secrets of our program –Reverse engineering is possible but very time- consuming

52 Intellectual Property Issues (I) Law protects programs in two ways –They can be trade secrets Protection ends once secret is revealed. –The can be copyrighted Only protects expressions of an idea Others can write a program doing the same things are your program using different instructions

53 Intellectual Property Issues (II) Selling C programs or Python programs is a very risky proposition –Invites imitators Best solution is –Selling copies of executables Properly obfuscated –Keeping source code secret

54 Interpreted languages (I) Languages like Basic, Perl, Python and Ruby are not compiled –Translated into bytecode before being executed –Bytecode is interpreted by the language interpreter

55 Interpreted languages (II) Python Interpreter: translates program into bytecode then executes it Python ProgramBytecode

56 Advantages Platform independence: –Bytecode can run on any platform for which there is an interpreter Dynamic typing: –Same variable can refer to a string then an integer then … Smaller executable sizes

57 Disadvantages Portability limitations : –Bytecode will not run run on any machine on which the interpreter was not installed. Speed: –Bytecode is not optimized for a specific architecture – Just-in-time compilation introduces delays Cannot sell a copies of a program without revealing its source code

58 A partial solution In many cases, speed is not an issue outside of loops than get executed thousand and thousands of times Loops inside other loops Can rewrite code for these inner loops in C and include this code into a Python program – Use Python C API

59 Neither fish nor fowl Java is compiled –Like Fortran, C, … into bytecode –Like Perl and Python Bytecode is executed by Java Virtual Machine


Download ppt "COSC 1306—COMPUTER SCIENCE AND PROGRAMMING FLOATING-POINT NUMBERS Jehan-François Pâris"

Similar presentations


Ads by Google