CS 101 Computer Programming and Utilization Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lecture 5, More Numerical computing (Slides courtesy Prof Ranade) IIT BOMBAY
CS 101
Computer Programming and Utilization
Dr Deepak B Phatak
Subrao Nilekani Chair Professor
Department of CSE, Kanwal Rekhi Building
IIT Bombay
Lecture 5, More Numerical computing
(Slides courtesy Prof Ranade)
IIT BOMBAY
Dr. Deepak B Phatak 2
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Overview
• Review of CPP Dumbo
• Iterative Numerical computations
•Factorial of a given integer
•Hemachandra Numbers
•Finding roots of an equation
• Course and Lab organization
Dr. Deepak B Phatak 3
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
C++ program structure
#include <iostream>
using namespace std;
int main(){
---
--- statements/instructions;
---
return(0);
}
• We will learn later what each of these lines mean. Right now, this is a mandatory structure
Dr. Deepak B Phatak 4
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
C++ Data types
• We have seen numerical and string data
7.45, 12.3E-12, “Ranade”, “\n”,
• Constant values are written like this by us
C++ stores these in an internal format
• Numerical values have an associated type
int, long, float, double
• Memory location names, called variables,
must be predefined with associated data type
int count; float a, b, sum; double largevalue;
Dr. Deepak B Phatak 5
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
C++ statements
• Each instruction of our program can ordinarily convey any one of the 3 actions
•Assignment, input, output
• Assignement
sum = a + b;
area = (x-1.0)*(1/(x-1.0);
m = m + x/2.5
•The last one is to be seen as “reassignment”
Dr. Deepak B Phatak 6
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
C++ statements ...
• “increment” is special form of reassignment
count = count + 1;
or count += 1;
or, more simply, ++count or count++
• Input
cin >> x >> maxvalue;
• Output
cout << “Value of y is “ << y << “\n”;
Dr. Deepak B Phatak 7
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Conditional execution
• Program instructions are normally executed in
the given sequence
• C++ can examine conditions, and based on the
result, can execute conditions out of sequence
if (condition)
{ statement group 1};
else
{ statement group 2};
Dr. Deepak B Phatak 8
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Conditional execution ...
• Based on the age of a passenger, the ticket
cost is different. Let us say, it is Rs 25.50 for
an adult, and Rs 12.75 for a child (< 12 Years)
cin >> age;
ticket = 12.75;
ticket = 25.50;
cout << “Rs. “ << ticket << endl;
Dr. Deepak B Phatak 9
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Conditional execution ...
• Suppose we alter the sequence of assigning a value to ticket
cin >> age;
ticket = 25.50;
ticket = 12.75;
cout << “Rs. “ << ticket << endl;
• The assignment to variable ticket will always be the last assigned value irrespective of age!
Dr. Deepak B Phatak 10
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Conditional execution …
• Use of the if – else statements will permit us to correctly evaluate the ticket
cin >> age;
if (age > 12)
{ticket = 25.50};
else
{ticket = 12.75};
cout << “Rs. “ << ticket << endl;
• What if elders are charged Rs 20?
Dr. Deepak B Phatak 11
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
If – else if ladder
cin >> age;
if (age > 60){
ticket = 20.00;}
else if (age > 12){
ticket = 25.50;}
else {
ticket = 12.75;}
cout << “Rs. “ << ticket << endl;
Dr. Deepak B Phatak 12
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Repetitive actions
int nfactorial, n, i
cin >> n
nafactorial = 1;
for (i =1; i <= n, i++){
nfactorial = nfactorial * i;
};
cout << “factorial ” << n << “ is ” << nfactorial;
Dr. Deepak B Phatak 13
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Complete program for n!
#include <iostream>
using namespace std;
int main() {
int nfactorial, n, i;
cout << “ Give value of n” << endl;
cin >> n;
Dr. Deepak B Phatak 14
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Complete program for n! …
nafactorial = 1;
for (i =1; i <= n, i++){
nfactorial = nfactorial * i;
};
cout <<“factorial ”<<n<< “is ”<<nfactorial<< endl;
Return(0);
}
Dr. Deepak B Phatak 15
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Hemachandra’s Problem (12th century AD)
Suppose I have to build a wall of length 8 feet. I have bricks 2 feet long and also 1 foot long. In how many ways I can lay the bricks so that I fill the 8 feet?
Possibilities:
2,2,2,2;
1,1,1,1,1,1,1,1;
2,2,2,1,1
....
Dr. Deepak B Phatak 16
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Hemachandra’s Actual Problem
Suppose I am designing a poetic meter with 8 beats. The meter is made of short syllables and long syllables.
Short syllable (s) = 1 beat,
Long syllable (l) = 2 beats.
How many ways are there of filling 8 beats?
Example of a poetic meterya kun den du tu sha r ha r dha va la ya shubh r vas tra vru ta
l l l s s l s l s s s l l l s l l s s
Dr. Deepak B Phatak 17
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Hemachandra’s Solution
“By the method of Pingala, it is enough to
observe that the last beat is long or short”
Pingala: mathematician/poet from 500 A.D.
Hemachandra is giving credit to someone who
lived hundreds of years before him!!
Copy if necessary and if permitted,
but always give credit
Dr. Deepak B Phatak 18
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Hemachandra’s solution contd.
S : Class of 8 beat patterns with short last beat.
L : Class of 8 beat patterns with long last beat.
Each 8 beat pattern is in class L or class S
S = all 7 beat patterns + short beat appended.
L = all 6 beat patterns + long beat appended
| class S | = Number of patterns with 7 beats
| class L | = Number of patterns with 6 beats
|8 beat patterns| = |class S| + |class L|
= |7 beat patterns| + |6 beat patterns|
Dr. Deepak B Phatak 19
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Algebraically..
Hn = number of patterns with n beats
H8 = H7 + H6
In general Hn = Hn-1 + Hn-2
Does this help us to compute H8?
We need to know H7, H6, for which we need H5, ...
Dr. Deepak B Phatak 20
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Algorithm Idea
H1 = number of patterns with 1 beat = 1 {S}
H2 = Number with 2 beats = 2 {SS, L}
H3 = H2 + H1 = 2 + 1 = 3 {SSS, SL, LS}
H4 = H3 + H2 = 3 + 2 = 5
H5 = H4 + H3 = 5 + 3 = 8
H6 = H5 + H4 = 8 + 5 = 13
H7 = H6 + H5 = 13 + 8 = 21
H8 = H7 + H6 = 21 + 13 = 34 ...
Dr. Deepak B Phatak 21
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Program to compute Hn
int n; cin >> n; // which number to compute
int hprev = 1, hcurrent = 2;
for(int i=3; i <= n; i++){
hnext = hprev + hcurrent;
// prepare for next iteration
hprev = hcurrent;
hcurrent = hnext; }
cout << hnext;
Dr. Deepak B Phatak 22
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Code is tricky!
Need a comment:
/* At the begining of an iteration
hcurrent = Hi-1 write ith term if you like.
hprev = Hi-2
where i is the value of variable i */
Can you prove this?
Will mathematical induction help?
Proving this is enough
-- hnext = hprev + hcurrent –
hence correct answer will be generated.
Dr. Deepak B Phatak 23
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Proof by induction
Base case: At the beginning of the first iteration is this true? Yes, i will have value 3, and hprev = 1 = H1, hcurrent = 2 = H2
Suppose it is true at some later iteration, when i has value v >= 3. By induction hypothesis, hprev and hcurrent have values Hv-1, Hv-2 respectively
The first statement hnext = hprev + hcurrent makes hnext = Hv-1 + Hv-2 = Hv. After this the statement hprev = hcurrent makes hprev = Hv-1. The next statement hcurrent = hnext makes hcurrent=Hv.
In the next iteration i will have value v+1. But hprev,hcurrent will have exactly the right values!
Dr. Deepak B Phatak 24
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
On Hemachandra Numbers
Mathematics from poetry!
Series is very interesting.
- Number of petals in many flowers.
- Ratio of consecutive terms tends to a limit.
What are these numbers more commonly known as?
Fibonacci numbers!!
Hemachandra lived before Fibonacci.
Dr. Deepak B Phatak 25
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Newton Raphson method
Method to find the root of f(x), i.e. x s.t. f(x)=0.
Method works if:
f(x) and f '(x) can be easily calculated.
A good initial guess is available.
Example: To find square root of k.
use f(x) = x2 - k. f’ (x) = 2x.
f(x), f’ (x) can be calculated easily.
2,3 arithmetic operations
Initial guess x0 = 1 always works! can be proved.
Dr. Deepak B Phatak 26
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
How to get better xi+1 given xi
f(x)
xi
xi+1
Point A =(xi,0) known.
A
B
C
f’ (xi) = AB/AC = f(xi)/(xi - xi+1) xi+1
= (xi- f(xi)/f’ (xi))
Calculate f(xi).
Point B=(xi,f(x
i)) known
Approximate f by tangent
C= intercept on x axis
C=(xi+1
,0)
Dr. Deepak B Phatak 27
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Square root of k
xi+1
= (xi- f(xi)/f’ (xi))
f(x) = x2 - k, f’ (x) = 2x
xi+1 = xi - (xi2 - k)/(2xi) = (xi + k/xi)/2
Starting with x0=1, we compute x1, then x2, then...
We can get as close to sqrt(k) as required.
Proof not part of the course.
Dr. Deepak B Phatak 28
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Code
float k;
cin >> k;
float xi=1; // Initial guess. Known to work.
for(int i=0; i < 10; i++){
// 10 iterations
xi = (xi + k/xi)/2;
}
cout << xi;
Dr. Deepak B Phatak 29
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Another way
float xi, k; cin >> k;
for( xi = 1 ;
// Initial guess. Known to work.
xi*xi – k > 0.001 || k - xi*xi > 0.001 ;
// until error in the square is at most 0.001
xi = (xi + k/xi)/2);
cout << xi;
Dr. Deepak B Phatak 30
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Yet Another way
float k; cin >> k;
float xi=1;
while(xi*xi – k > 0.001 || k - xi*xi > 0.001){
xi = (xi + k/xi)/2 ;
}
cout << xi;
}
Dr. Deepak B Phatak 31
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
While statement
while (condition) { loop body}
check condition, then execute loop body if true.
Repeat.
If loop body is a single statement, then need not
use { }. Always putting braces is recommended;
if you insert a statement, you may forget to put
them, so do it at the beginning.
True for other statements also: for/repeat/if.
Dr. Deepak B Phatak 32
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
For vs. while
If there is a “control” variable with initial value,
update rule, and whose value distinctly defines
each loop iteration, use for.
If loop executes fixed number of times, use for.
Dr. Deepak B Phatak 33
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Homework
Write a program to calculate the cube root
using Newton Raphson method.
Check how many iterations are needed to get
good answers. Should be very few.
Dr. Deepak B Phatak 34
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
evaluation approach for CS101
Quizzes 10%
Assignments 10%
Course Project 30%
Mid-semester exam 20%
End Semester Exam 30%
Minimum passing grade (DD) at >= 40% marks
Dr. Deepak B Phatak 35
IIT BOMBAY
CS 101 - Lecture 5 More numerical Computing
Consulting support
Monday 13:30 to 17:30
Tuesday 13:30 to 17:30
TAs will be available to help you with
your queries regarding lectures/labs and
with programming problems
Additional hours for lab access on both
these days
//possibly also Thursday 13:30 to 17:30
// will be announced tomorrow