• No results found

•Hemachandra Numbers

N/A
N/A
Protected

Academic year: 2022

Share "•Hemachandra Numbers"

Copied!
35
0
0

Loading.... (view fulltext now)

Full text

(1)

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

IIT BOMBAY

(2)

IIT BOMBAY

Overview

• Review of CPP Dumbo

• Iterative Numerical computations

•Factorial of a given integer

•Hemachandra Numbers

•Finding roots of an equation

• Course and Lab organization

(3)

IIT BOMBAY

C++ program structure

#include <iostream>

using namespace std;

int main(){

---

--- statements/instructions;

---

return(0);

}

• We will learn later what each of these lines

(4)

IIT BOMBAY

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

(5)

IIT BOMBAY

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”

(6)

IIT BOMBAY

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”;

(7)

IIT BOMBAY

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};

(8)

IIT BOMBAY

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;

(9)

IIT BOMBAY

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!

(10)

IIT BOMBAY

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?

(11)

IIT BOMBAY

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;

(12)

IIT BOMBAY

Repetitive actions

int nfactorial, n, i cin >> n

nafactorial = 1;

for (i =1; i <= n, i++){

nfactorial = nfactorial * i;

};

cout << “factorial ” << n << “ is ” << nfactorial;

(13)

IIT BOMBAY

Complete program for n!

#include <iostream>

using namespace std;

int main() {

int nfactorial, n, i;

cout << “ Give value of n” << endl;

cin >> n;

(14)

IIT BOMBAY

Complete program for n! …

nafactorial = 1;

for (i =1; i <= n, i++){

nfactorial = nfactorial * i;

};

cout <<“factorial ”<<n<< “is ”<<nfactorial<< endl;

Return(0);

}

(15)

IIT BOMBAY

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 ....

(16)

IIT BOMBAY

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 meter

ya 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

(17)

IIT BOMBAY

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

(18)

IIT BOMBAY

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|

(19)

IIT BOMBAY

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, ...

(20)

IIT BOMBAY

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 ...

(21)

IIT BOMBAY

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;

(22)

IIT BOMBAY

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.

(23)

IIT BOMBAY

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!

(24)

IIT BOMBAY

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.

(25)

IIT BOMBAY

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

(26)

IIT BOMBAY

How to get better xi+1 given xi

f(x)

xi xi+1

Point A =(xi,0) known.

A B

C

Calculate f(xi ).

Point B=(xi,f(xi)) known Approximate f by tangent C= intercept on x axis C=(xi+1,0)

(27)

IIT BOMBAY

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.

(28)

IIT BOMBAY

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;

}

(29)

IIT BOMBAY

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;

(30)

IIT BOMBAY

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;

}

(31)

IIT BOMBAY

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.

(32)

IIT BOMBAY

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.

(33)

IIT BOMBAY

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.

(34)

IIT BOMBAY

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

(35)

IIT BOMBAY

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

References

Related documents

Accuracy for a loop with N iterations = (N-2)/N + Loop branches for loops with large number

• If the condition is true originally, then the value of some variable used in condition must change in the execution of body, so that eventually condition becomes false. •

• If the condition is true originally, then the value of some variable used in condition must change in the execution of body, so that eventually condition becomes false. •

• If there is no difference between the economic value of inputs and outputs and the social value of those, the UNIDO approach for project evaluation ends at stage four. •

We seek an assignment such that (a) if the value of each data item is within its data accuracy bound at a coordinator then the value of each query is also within its accuracy bound,

● We can use a value of a subtype wherever a value of the (super) type is expected. ● This is stated by the following rule

Non-use values: Many people value the coastal areas and estuarine wetlands even if they are living far away from the coasts or even if they never plan to visit or use the goods

 For each data item Q, if Ti executes read(Q) in schedule S1, and if that value was produced by a write(Q) executed by transaction Tj, then the read(Q) of Ti must also read the