Even-odd series

A mathematical sequence is defined as:

\(x_1 = 0.1\)

\(x_{i} = \begin{cases} x_{i-1} + 0.1 , & \mbox{if } i-1 \mbox{ is even} \\ x_{i-1} + 0.2 , & \mbox{if } i-1 \mbox{ is odd} \\ \end{cases}\)

Write the function evenodd() that given a value v and a tolerance epsilon, returns the number of terms of the sequence, beginning from \(x_1\), which must be added to get the exact value v with a tolerance epsilon. In case the sum of terms never gives this value with this precision, the function will return -1. Keep in mind that it is a increasing series.

For example, for v= 1.4 the function will return 4, because the sum of the 4 first terms of the sequence (0.1+0.3+0.4+0.6) is exactly 1.4:

\[\begin{split}\begin{array}{l} x_1 = 0.1 \\ x_2 = x_1 + 0.2 = 0.1 + 0.2 = 0.3 \\ x_3 = x_2 + 0.1 = 0.3 + 0.1 = 0.4 \\ x_4 = x_3 + 0.2 = 0.4 + 0.2 = 0.6 \\ \end{array}\end{split}\]

Save the function into file series.py. Examples:

>>> even_odd(1.4,0.001)
4
>>> even_odd(1.5,0.001)
-1
>>> even_odd(34.1,0.0001)
21
>>> even_odd(34.1,0.000000000000001)
-1

Note

You can download the file with tests even-odd.txt

Solution

A solution of these functions is provided in the series.py