Function sampling

In these exercises we want to sample a function f in a given interval [a, b] and with d increments. a, b and d are such that \(a < b\) and \(d < b-a\). Sampling f consists in computing points of this function with abscissas beginning with x=a, with uniform increments of d, and such all of them are less than or equal to b. Values a, b and d can be real.

Save the following functions into file sampling.py.

  1. Write the function positives(a, b, d, k) that returns the average of the function f values (ordinates of the sampled points) in the given interval which are positive. Function f is defined as: \(f(x, k) = e^{\frac{x}{k}} - k sin(x)\), \(k >0\). If there is no positive value, this function must return 0.0. Examples:

    >>> round(positives(-20, 10, 0.1, 2), 2)
    15.3
    >>> round(positives(-20, 10, 0.1, 15), 2)
    9.76
    

    Note

    More tests can be found in file positives.txt

  2. Write the function localmax(a, b, d, k) that returns a list of tuples where each tuple is the coordinates pair (x, y) of those points that are local maxima of the function \(f(x, k) = e^{\frac{x}{k}} - k sin(x)\), \(k >0\) in the given interval. A point (x, y) is a local maxima if its ordinate is greater than the ordinate of the previous sampled point and of that of the next one. Examples:

    >>> lmin = localmax(-20, 10, 0.1, 2)
    >>> for x, y in lmin:
    ...    print(round(x, 2), round(y, 2))
    -14.1 2.0
    -7.8 2.02
    -1.4 2.47
    
    >>> lmin = localmax(-20, 10, 0.1, 15)
    >>> for x, y in lmin:
    ...    print(round(x, 2), round(y, 2))
    -14.1 15.38
    -7.9 15.57
    -1.6 15.89
    4.7 16.37
    

    Note

    More tests can be found in file localmax.txt

  3. Write the function fposneg (a, b, k, n) that returns the number of sampled positive or zero values and the number of sampled negative values of function \(f(x, k) = e^{\frac{x}{k}} - k sin(x)\), \(k >0\) in the given interval. In this case n stands for the number of points to be sampled (including the interval extreme points). Examples:

    >>> fposneg(-20, 10, 2, 31)
    (21, 10)
    >>> fposneg(-20, 10, 15, 61)
    (30, 31)
    

    Note

    More tests can be found in file fposneg.txt

Solution

Solutions can be found in file sampling.py