Floating-Point

advertisement
COSC 1306—COMPUTER
SCIENCE AND PROGRAMMING
FLOATING-POINT NUMBERS
Jehan-François Pâris
jfparis@uh.edu
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
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))
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
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
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
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 )
Example (II)
• Program prints
pi equals 3.1
pi equals 3.14
pi equals 3.142
pi equals 3.1416
• Values are nicely rounded
Converting oF into oC (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))
Converting oF into oC r (II)
• Output is
Enter a temperature in degrees Fahrenheit: 100
100.0 degrees F equals 37.8 degrees C
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
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))
Example (II)
• Output is:
What's your name? Bill
How many classes are you taking? 5
Bill is taking 5 classe(s)
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?')
More escapes
• Escape sequence
\'
\"
\\
\n
\r
• (See page 86)
Meaning
Apostrophe
Double quote
Backslash
Newline
Carriage return
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
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
Examples
>>> a = 3
>>> b = 5
>>> p = (a < b)
>>> q = (b <= a)
>>> print("p = " + str(p) + “ and q = " +str(q))
p = True and q = False
Boolean operations (I)
• AND:
– True if both operands are true
a
F
F
T
T
b
F
T
F
T
a and b
F
F
F
T
This is called
a truth table
Boolean operations (II)
• OR:
– True unless both operands are false
a
F
F
T
T
b
F
T
F
T
a or b
F
T
T
T
Boolean operations (III)
• NOT:
– True if operand is false
a not a
F T
T F
Boolean operations (IV)
• Equality/Mutual Implication:
– True when both operands are equal
– Represented by a == sign
a
F
F
T
T
b
F
T
F
T
a==b
T
F
F
T
Boolean operations (V)
• Inequality/Exclusive OR (XOR):
– True when operands are not equal
– Represented by a != sign
a
b a!=b
F
F
T
T
F
T
F
T
F
T
T
F
Notes
• XOR is used for
– Generating parity bits
– Hardware hashing
Examples
• Assuming P is True and q is False
>>> p or q
True
>>> p and q
False
>>> not p
False
>>> p != q
True
Variables and objects
• Variables point to objects
– Integers
– Strings
– Floating-point numbers
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
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
–…
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
Examples (I)
>>> a = 'bill'
>>> a.capitalize()
'Bill'
>>> b = 'Bill'
>>> b.capitalize()
'Bill'
Examples (II)
>>> c = 'bILL'
>>> c.capitalize()
'Bill'
>>> d ='Billy Bob'
>>> d.capitalize()
'Billy bob‘
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
Examples (I)
>>> s = 'biLLy Bob'
>>> s.title()
'Billy Bob'
>>> s ='jehan-francois'
>>> s.title()
'Jehan-Francois'
>>> s.title()
Examples
>>> s = "dean's list"
>>> s.title()
"Dean'S List"
>>> s
"dean's list"
>>>
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
"""
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
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) '
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!')
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!
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!
Examples (I)
>>> i=1
>>> i += 1
>>> print(i)
2
>>> i++
SyntaxError: invalid syntax
>>> ++i
2
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) '
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 -)
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)
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
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)
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!
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
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
Compiled languages (II)
C program
C compiler
Executable
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 timeconsuming
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
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
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
Interpreted languages (II)
Python Program
Bytecode
Python Interpreter:
translates program into bytecode
then executes it
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
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
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
Neither fish nor fowl
• Java is compiled
– Like Fortran, C, …
into bytecode
– Like Perl and Python
• Bytecode is executed by Java Virtual Machine
Download