Home Lesson-3.6

Lesson-3.5

Library

We will look at two more libraries — math and random — and use them to solve some fascinating problems in mathematics.

 

math

Consider the following sequence:

Mathematically, it is known that this sequence converges or approaches a specific value. In other words, this sequence gets closer and closer to a well defined number as more terms are added. This number is called the limit of the sequence. What is the limit for the above sequence? Can we use whatever we have learned so far to estimate this value?

If we execute the above code, we get the following output:

sqrt is a function in the math library that returns the square root of the number that is entered as argument. Representing the output shown above as a table:

Approximate value
11.414
21.848
31.962
41.990
51.998

Isn't that beautiful? It looks like this sequence — the train of square roots — is approaching the value 2. Let us run the loop for more number of iterations this time:

After just 20 iterations, the value is so close to two: 1.9999999999910236. But we have used trial and error to decide when to terminate the iteration. A better way to do this is to define a tolerance: if the difference between the previous value and the current value in the sequence is less than some predefined value (tolerance), then we terminate the iteration.

 

random

How do we toss a coin using Python?

That is all there is to it! random is a library and choice is a function defined in it. It accepts any sequence as input and returns an element chosen at random from this sequence. In this case, the input is a string, which is nothing but a sequence of characters.

We know that the probability of obtaining a head on a coin toss is 0.5. This is the theory. Is there a way to see this rule in action? Can we computationally verify if this is indeed the case? For that, we have to set up the following experiment. Toss a coin times and count the number of heads. Dividing the total number of heads by will give the empirical probability. As becomes large, this probability must approach 0.5.

Let us run the above code for different values of and tabulate our results:

100.2
1000.52
1,0000.517
10,0000.5033
100,0000.49926
1,000,0000.499983

The value is approaching 0.5 as expected! random is quite versatile. Let us now roll a dice!

randint(a, b) returns a random integer such that . We can do a similar experiment for finding the probability of obtaining a number, say 1, when a dice is thrown.