""" Lecture 2 : Some programming concepts; intro to using mathematical functions in python. ---------------- Date : 06 Jan 2013 """ # Here are a few concepts from programming. First one boots into an # operating system. The operating system has different applications. We are # interested in a text editing software and a python interpreter. # # The text editing software is a program which allows you to create, edit # and save text files. Nowadays most text editors do much more than that. # For example, they support syntax highlighting, auto-indentation, and some # even allow you to run the code from within the editor (for example vim or # emacs). The other application we are interested in is a python # interpreter. This comes pre-installed in linux. Windows and mac users can # get it from http://www.python.org . """ Some computing terms : Program / code : the instructions you give the interpreter/compiler. function : a code which you can "call" from another code. Module : a set of functions which someone has written and you can use them in your programs. package : a collection of related modules packaged together for easy distribution. algorithm : a step by step account of how to compute something in plain english. pseudo-code : A text which looks like code but is in english. It is something in between english description and an actual code. bug : an programming error in the code. statement : a code comprises of statements. Statements are individual instructions like a = 4 (assignment) print t (print statement) a = input("Something") (input statement) etc. To emphasaize again: = is an assignment, not a mathematical equality. Everything is CASE SENSITIVE. aa, aA, Aa are different names. """ # Precedence of arithmetic operators. # ** is evaluated first (left to right) then *, / and after that +, -. # importing modules : math # Problem : Consider the vertical motion of a ball. Suppose h = 0 at time t # = 0, and g = 9.8 m/s/s . Let v0 be the initial velocity. Then the height # at time t is given by t = 1.0 v0 = -1.0 g = - 9.8 h = v0 * t + 0.5 * g * t**2 print "Height at time t = %g is %g" % (t, h) # Now suppose we want to know the time when it reaches say height hfin = 1. # We know the formula for t for which # 0.5 g t^2 + v0 t - hfin = 0 # it is # t = (-v0 \pm sqrt(v0^2 + 4 * 0.5 g * hfin)) / g # Let us code it import math hfin = 1.0 t1 = (-v0 + math.sqrt(v0**2 - 2 * g * hfin)) / g t2 = (-v0 - math.sqrt(v0 ** 2 - 2 * g * hfin)) / g print "The time is either %g or %g" % (t1, t2) # you can also use from math import * print "Square root of 100 is %g." % sqrt(100)