﻿
1.8 Summary
41
•veriﬁcation:providingevidencethattheprogramworkscorrectly
•debugging:locatingandcorrectingerrorsinaprogram
1.8.2Example:Trajectoryofaball
Problem. Whatisthetrajectoryofaballthatisthrownorkickedwith
aninitialvelocityv
0
makinganangleθwiththehorizontal?Thisproblem
canbesolvedbybasichighschoolphysicsasyouareencouragedtodo
inExercise1.13.Theballwillfollowatrajectoryy=f(x)throughthe
airwhere
f(x)=xtanθ−
1
2v2
0
gx2
cos2θ
+y
0
.
(1.6)
Inthisexpression,xisahorizontalcoordinate,gistheaccelerationof
gravity,v
0
isthesizeoftheinitialvelocitythatmakesanangleθwith
thexaxis,and(0,y
0
)istheinitialpositionoftheball.Ourprogramming
goalistomakeaprogramforevaluating(1.6).Theprogramshouldwrite
outthevalueofalltheinvolvedvariablesandwhattheirunitsare.
Weremarkthattheformula(1.6)neglectsairresistance.Exercise1.11
exploreshowimportantairresistanceis.Forasoftkick(v
0
=10km/h)
resistance.Forahardkick,airresistancemaybeasimportantasgravity.
Solution. WeusetheSIsystemandassumethatv
0
isgiveninkm/h;
g=9.81m/s
2
;x,y,andy
0
aremeasuredinmeters;andθindegrees.The
programhasnaturallyfourparts:initializationofinputdata,importof
functionsandπfrommath,conversionofv
0
respectively,andevaluationoftheright-handsideexpressionin(1.6).We
choosetowriteoutallnumericalvalueswithonedecimal.Thecomplete
programisfoundintheﬁletrajectory.py:
g = = 9.81
# m/s**2
v0 = = 15
# km/h
theta = = 60 0 # # degrees
x = = 0.5
# m
y0 = = 1
# m
print """\
v0
= %.1f f km/h
theta = = %d degrees
y0
= %.1f f m
x
= %.1f f m\
""" % % (v0, , theta, y0, x)
from math import pi, , tan, cos
# Convert v0 to m/s and theta to o radians
v0 = = v0/3.6
theta = = theta*pi/180
y = = x*tan(theta) ) - 1/(2*v0**2)*g*x**2/((cos(theta))**2) + + y0
print ’y
= %.1f f m’ % % y
Pdf form creator - C# PDF Field Edit Library: insert, delete, update pdf form field in C#.net, ASP.NET, MVC, Ajax, WPF
Online C# Tutorial to Insert, Delete and Update Fields in PDF Document
add fields to pdf; allow users to save pdf form
Pdf form creator - VB.NET PDF Field Edit library: insert, delete, update pdf form field in vb.net, ASP.NET, MVC, Ajax, WPF
How to Insert, Delete and Update Fields in PDF Document with VB.NET Demo Code
best pdf form creator; cannot save pdf form
42
1 Computingwithformulas
Thebackslashinthetriple-quotedmulti-linestring makesthe string
continueonthenextlinewithoutanewline.Thismeansthatremoving
thebackslashresultsinablanklineabovethev0lineandablankline
betweenthexandylinesintheoutputonthescreen.Anotherpointto
mentionistheexpression1/(2*v0**2),whichmightseemasacandidate
forunintendedintegerdivision.However,theconversionof v0tom/s
2*v0**2beingfloat.Therestoftheprogramshouldbeself-explanatory
atthisstageinthebook.
We can execute the program in IPythonor an ordinary y terminal
windowandwatchtheoutput:
Terminal
v0
= 15.0 km/h
theta = = 60 0 degrees
y0
= 1.0 m
x
= 0.5 m
y
= 1.6 m
Thisversionofthebookappliesdiﬀerentdesignelementsfordiﬀerent
typesof“computertext”.Completeprogramsandpartsofprograms
(snippets)aretypesetwithalightbluebackground.Asnippetlookslike
this:
a = = sqrt(4*p p + + c)
print ’a =’, a
C = = 21
F = = (9.0/5)*C + + 32
print F
programyoucantryoutorifitisjustapartofaprogram(asnippet)so
totrythecodeoutyourself.Theappearanceofaverticallinetotheleft
ornotwillthenquicklytellyouwhattypeofcodeyousee.
AninteractivePythonsessionistypesetas
>>> from m math h import *
>>> p p = = 1; c c = = -1.5
>>> a a = = sqrt(4*p p + + c)
Runningaprogram,sayball_yc.py,intheterminalwindow,followed
bysomepossibleoutputistypesetas
Terminal
C# Create PDF Library SDK to convert PDF from other file formats
Tell Users How to Create New PDF File and Load PDF from Other Files. Free PDF creator SDK for Visual Studio .NET. C# Project: PDF Creator Library DLLs.
create a form in pdf from word; add attachment to pdf form
VB.NET Create PDF Library SDK to convert PDF from other file
Free PDF creator SDK library compatible with Visual Basic .NET class and able to create PDF in both .NET WinForms and ASP.NET program.
adding images to pdf forms; add form fields to pdf without acrobat
1.9 Exercises
43
ball_yc.py
At t=0.0417064 s and 0.977662 2 s, , the height is 0.2 m.
RecallfromSection1.5.3thatwejustwritetheprogramname.Areal
executiondemandspreﬁxingtheprogramnamebypythoninaterminal
window,orbyrunifyouruntheprogramfromaninteractiveIPython
session.WerefertoAppendixH.2for morecompleteinformationon
runningPythonprogramsindiﬀerentways.
Sometimesjusttheoutputfromaprogramisshown,andthisoutput
appearsasplaincomputertext:
h = = 0.2
order=0, error=0.221403
order=1, error=0.0214028
order=2, error=0.00140276
order=3, error=6.94248e-05
order=4, error=2.75816e-06
Filescontainingdataareshowninasimilarwayinthisbook:
date
Oslo
London
Berlin
Paris
Rome
Helsinki
01.05 18
21.2
20.2
13.7
15.8
15
01.06 21
13.2
14.9
18
24
20
01.07 13
14
16
25
26.2
14.5
StyleguideforPythoncode. ThisbookpresentsPythoncodethatis
(mostly)inaccordancewiththeoﬃcialStyleGuideforPythonCode
5
,
knowninthePythoncommunityasPEP8.Someexceptionstotherules
andlessblanklines.
1.9Exercises
Whatdoesitmeantosolveanexercise? Thesolutiontomostofthe
exercisesinthisbookisaPythonprogram.Toproducethesolution,you
ﬁrst need understand the problem and what the program is supposed
to do, and then you need to understand how to translate the problem
description into a series of Python statements. Equally important is
the veriﬁcation (testing) of the program. A complete solution to a pro-
gramming exercises therefore consists of two parts: 1) the program text
and 2) a demonstration that the program works correctly. Some simple
programs, like the ones in the ﬁrst two exercises below, have so obviously
correct output that the veriﬁcation can just be to run the program and
record the output.
In cases where the correctness of the output is not obvious, it is
necessary to prove or bring evidence that the result is correct. This can
be done through comparisons with calculations done separately on a
calculator, or one can apply the program to a special simple test case
5
http://www.python.org/dev/peps/pep-0008/
metadata.Keywords = "University, Public, etc."; metadata.Creator = "MS Office String inputFilePath = Program.RootPath + "\\" 1.pdf"; String outputFilePath
add editable fields to pdf; create a pdf form that can be filled out
VB.NET PDF - How to Add Barcode on PDF Page
add fillable fields to pdf; create a fillable pdf form from a pdf
44
1 Computing with formulas
with known results. The requirement is to provide evidence to the claim
that the program is without programming errors.
The sample run of the program to check its correctness can be inserted
at the end of the program as a triple-quoted string. Alternatively, the
output lines can be inserted as comments, but using a multi-line string
requires less typing. (Technically, a string object is created, but not
assigned to any name or used for anything in the program beyond
providing useful information for the reader of the code.) One can do
Terminal
Terminal> python myprogram.py > result
and use a text editor to insert the ﬁleresult inside the triple-quoted
multi-line string. Here is an example on a run of a Fahrenheit to Celsius
conversion program inserted at the end as a triple-quoted string:
F = 69.8
# Fahrenheit degrees
C = (5.0/9)*(F - 32)
# Corresponding Celsius degrees
print C
’’’
Sample run (correct result is 21):
python f2c.py
21.0
’’’
Exercise 1.1: Compute 1+1
The ﬁrst exercise concerns some very basic mathematics and program-
ming: assign the result of 1+1 to a variable and print the value of that
variable. Filename: 1plus1.py.
Exercise 1.2: Write a Hello World program
Almost all books about programming languages start with a very simple
program that prints the textHello, World! to the screen. Make such a
program in Python. Filename: hello_world.py.
Exercise 1.3: Derive and compute a formula
Can a newborn baby in Norway expect to live for one billion (109)
seconds? Write a Python program for doing arithmetics to answer the
question. Filename: seconds2years.py.
metadata.Keywords = "University, Public, etc." metadata.Creator = "MS Office Dim inputFilePath As String = Program.RootPath + "\\" 1.pdf" Dim outputFilePath
change text size pdf form; convert word document to editable pdf form
VB.NET PowerPoint: VB Codes to Create Linear and 2D Barcodes on
as 2d barcodes QR Code, Data Matrix, PDF-417, etc Imaging.Basic.dll", "RasterEdge. Imaging.Barcode.Creator.dll" and barcode, which will be in the form of REImage
add email button to pdf form; change font in pdf form
1.9 Exercises
45
Exercise 1.4: Convert from meters to British length units
Make aprogram where you set a length given in meters and then compute
and write out the corresponding length measured in inches, in feet, in
yards, and in miles. Use that one inch is 2.54 cm, one foot is 12 inches,
one yard is 3 feet, and one British mile is 1760 yards. For veriﬁcation, a
length of 640 meters corresponds to 25196.85 inches, 2099.74 feet, 699.91
yards, or 0.3977 miles. Filename: length_conversion.py.
Exercise 1.5: Compute the mass of various substances
The density of a substance is deﬁned as =m/V, wherem is the mass
of a volumeV . Compute and print out the mass of one liter of each of
the following substances whose densities ing/cm
3
are found in the ﬁle
src/files/densities.dat6:iron,air,gasoline,ice,the humanbody,
silver, and platinum. Filename: 1liter.py.
Exercise 1.6: Compute the growth of money in a bank
Letp be a bank’s interest rate in percent per year. An initial amountA
has then grown to
A
1+
p
100
n
aftern years. Makea program for computing how much money 1000euros
have grown to after three years with 5 percent interest rate. Filename:
interest_rate.py.
Exercise 1.7: Find error(s) in a program
Suppose somebody has written a simple one-line program for computing
sin(1):
x=1; print ’sin(%g)=%g’ % (x, sin(x))
Create this program and try to run it. What is the problem?
Exercise 1.8: Type in program text
Type the following program in your editor and execute it. If your program
does not work, check that you have copied the code correctly.
6
http://tinyurl.com/pwyasaa/files/densities.dat
VB.NET Imaging - Generate Barcode Image in VB.NET
Barcode creator SDK to write & customize ISSN barcode generation in VB.NET imaging project. ITF-14 valid for scanner reading on any pages in a PDF or TIFF
pdf form change font size; cannot save pdf form in reader
C# TIFF: Create Linear and 2D Barcodes on TIFF Document Using C#
TIFF Barcodes Creation. This C# TIFF Barcode Creator Add-on the supported barcode types are listed in the following form. C# TIFF Micro PDF-417 Creating, C# TIFF
pdf form creation; best way to create pdf forms
46
1 Computing with formulas
from math import pi
h = 5.0
# height
b = 2.0
# base
r = 1.5
area_parallelogram = h*b
print ’The area of the parallelogram is %.3f’ % area_parallelogram
area_square = b**2
print ’The area of the square is %g’ % area_square
area_circle = pi*r**2
print ’The area of the circle is %.3f’ % area_circle
volume_cone = 1.0/3*pi*r**2*h
print ’The volume of the cone is %.3f’ % volume_cone
Filename: formulas_shapes.py.
Exercise 1.9: Type in programs and debug them
Type these short programs in your editor and execute them. When they
do not work, identify and correct the erroneous statements.
a) Does sin2(x) +cos2(x) = 1?
from math import sin, cos
x = pi/4
1_val = math.sin^2(x) + math.cos^2(x)
print 1_VAL
b) Computesinmeterswhen s= v
0
t+0,5at
2
,withv
0
=3 m/s,t = 1
s, a = 2 m/s
2
.
v0 = 3 m/s
t = 1 s
a = 2 m/s**2
s = v0.t + 0,5.a.t**2
print s
c) Verify these equations:
(a +b)
2
=a
2
+2ab +b
2
(a −b)
2
=a
2
−2ab +b
2
a = 3,3
b = 5,3
a2 = a**2
b2 = b**2
eq1_sum = a2 + 2ab + b2
eq2_sum = a2 - 2ab + b2
eq1_pow = (a + b)**2
eq2_pow = (a - b)**2
Create Thumbnail in Web Image Viewer | Online Tutorials
Go to the toolbar: Select "Thumbnail Creator" & activate RasterEdge OCR Engine; PDF Reading; Encode & Decode JBIG Twain Scanning; DICOM Reading; Form Recognition
best way to make pdf forms; change font size pdf form
VB Imaging - Micro PDF 417 VB Barcode Generation
in a programming way. Following are the main features of this VB.NET Micro PDF 417 barcode creator SDK. The Barcode Creator Add-on
changing font size in pdf form field; pdf forms save
1.9 Exercises
47
print ’First equation: %g = %g’, % (eq1_sum, eq1_pow)
print ’Second equation: %h = %h’, % (eq2_pow, eq2_pow)
Filename: sin2_plus_cos2.py.
Exercise 1.10: Evaluate a Gaussian function
The bell-shaped Gaussian function,
f(x) =
1
2πs
exp
1
2
x− m
s
2
,
(1.7)
is one of the most widely used functions in science and technology. The
parametersm ands> 0 are prescribed real numbers. Make a program
for evaluating this function whenm = 0,s = 2, andx = 1. Verify the
program’s result by comparing with hand calculations on a calculator.
Filename: gaussian1.py.
Remarks. Thefunction(1.7)isnamedafterCarlFriedrichGauss
7
,1777-
1855, who was a German mathematician and scientist, now considered as
one of the greatest scientists of all time. He contributed to many ﬁelds,
including number theory, statistics, mathematical analysis, diﬀerential ge-
ometry, geodesy, electrostatics, astronomy, and optics. Gauss introduced
the function (1.7) when he analyzed probabilities related to astronomical
data.
Exercise 1.11: Compute the air resistance on a football
The drag force, due to air resistance, on an object can be expressed as
F
d
=
1
2
C
D
�AV
2
,
(1.8)
where is the density of the air,V is the velocity of the object,A is
the cross-sectional area (normal to the velocity direction), andC
D
is the
drag coeﬃcient, which depends heavily on the shape of the object and
the roughness of the surface.
The gravity force on an object with mass m is F
g
mg, where
g= 9.81ms
−2
.
We can use the formulas forF
d
andF
g
to study the importance of
air resistance versus gravity when kicking a football. The density of air
is = 1.2kg m−3. We haveA =πa2 for any ball with radiusa. For a
football, a = 11 cm, the mass is 0.43 kg, and C
D
can be taken as 0.2.
Make a program that computes the drag force and the gravity force
on a football. Write out the forces with one decimal in units of Newton
7http://en.wikipedia.org/wiki/Carl_Gauss
48
1 Computing with formulas
(N =kgm/s2). Also print the ratio of the drag force and the gravity force.
DeﬁneC
D
,,A,V,m,g,F
d
,andF
g
as variables, and put a comment
with the corresponding unit. Use the program to calculate the forces on
the ball for a hard kick,V = 120km/h and for a soft kick,V = 10km/h
(it is easy to mix inconsistent units, so make sure you compute withV
expressed in m/s). Filename: kick.py.
Exercise 1.12: How to cook the perfect egg
As an egg cooks, the proteins ﬁrst denature and then coagulate. When
the temperature exceeds a critical point, reactions begin and proceed
faster as the temperature increases. In the egg white, the proteins start
to coagulate for temperatures above 63 C, while in the yolk the proteins
start to coagulate for temperatures above 70 C. For a soft boiled egg,
the white needs to have been heated long enough to coagulate at a
temperature above 63 C, but the yolk should not be heated above 70 C.
For a hard boiled egg, the center of the yolk should be allowed to reach
70 C.
The following formula expresses the timet it takes (in seconds) for
the center of the yolk to reach the temperature T
y
(in Celsius degrees):
t=
M2/31/3
2(4π/3)2/3
ln
0.76
T
o
−T
w
T
y
−T
w
.
(1.9)
Here,M,ρ,c, andK are properties of the egg:M is the mass,ρ is the
density,c is the speciﬁc heat capacity, andK is thermal conductivity.
Relevant values areM = 47 gfor a smallegg andM =67 gfor alarge egg,
ρ=1.038 gcm−3, c=3.7 Jg−1K
−1
,andK = 5.4· 10−3 Wcm−1K
−1
.
Furthermore,T
w
is the temperature (in C degrees) of the boiling water,
andT
o
is the original temperature (in C degrees) of the egg before being
put in the water. Implement the formula in a program, setT
w
=100
CandT
y
=70 C, and computet for a large egg taken from the fridge
(T
o
=4 C) and from room temperature (T
o
=20 C). Filename: egg.py.
Exercise 1.13: Derive the trajectory of a ball
The purpose of this exercise is to explain how Equation (1.6) for the
trajectory of a ball arises from basic physics. There is no programming
in this exercise, just physics and mathematics.
The motion of the ball is governed by Newton’s second law:
F
x
=ma
x
(1.10)
F
y
=ma
y
(1.11)
1.9 Exercises
49
whereF
x
andF
y
are the sum of forces in thex andy directions, respec-
tively,a
x
anda
y
are the accelerations of the ball in thex andy directions,
andm is the mass of the ball. Let (x(t),y (t)) be the position of the ball,
i.e., the horizontal and vertical coordinate of the ball at timet. There
are well-known relations between acceleration, velocity, and position: the
acceleration is the time derivative of the velocity, and the velocity is the
time derivative of the position. Therefore we have that
a
x
=
d2x
dt2
,
(1.12)
a
y
=
d2y
dt2
.
(1.13)
If we assume that gravity is the only important force on the ball,F
x
=0
and F
y
=−mg.
Integrate the two components of Newton’s second law twice. Use the
initial conditions on velocity and position,
d
dt
x(0) = v
0
cos θ,
(1.14)
d
dt
y(0) = v
0
sinθ,
(1.15)
x(0) = 0,
(1.16)
y(0) = y
0
,
(1.17)
to determine thefour integration constants. Write up the ﬁnalexpressions
forx(t) andy(t). Show that ifθ =π/2, i.e., the motion is purely vertical,
we get the formula (1.1) for they position. Also show that if we eliminate
t,weendupwiththerelation(1.6)betweenthe xand ycoordinates
of the ball. You may read more about this type of motion in a physics
book, e.g., . Filename: trajectory.*.
Exercise 1.14: Find errors in the coding of formulas
Some versions of our program for calculating the formula (1.3) are listed
below. Find the versions that will not work correctly and explain why in
each case.
C = 21;
F = 9/5*C + 32;
print F
C = 21.0; F = (9/5)*C + 32;
print F
C = 21.0; F = 9*C/5 + 32;
print F
C = 21.0; F = 9.*(C/5.0) + 32;
print F
C = 21.0; F = 9.0*C/5.0 + 32;
print F
C = 21;
F = 9*C/5 + 32;
print F
C = 21.0; F = (1/5)*9*C + 32;
print F
C = 21;
F = (1./5)*9*C + 32;
print F